Java's Collection Framework

From this document you will learn the answers to the following questions:

Abstract Data Type is a type of what?

What does this method do?

What type of type is abstract Data Type?

Similar documents
Class 32: The Java Collections Framework

Collections in Java. Arrays. Iterators. Collections (also called containers) Has special language support. Iterator (i) Collection (i) Set (i),

Working with Java Collections

Data Structures in the Java API

The Java Collections Framework

Datastrukturer och standardalgoritmer i Java

JAVA COLLECTIONS FRAMEWORK

Software Engineering II. Java 2 Collections. Bartosz Walter <Bartek.Walter@man.poznan.pl>

Per imparare a programmare bisogna programmare

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

Practical Session 4 Java Collections

CSE 2123 Collections: Sets and Iterators (Hash functions and Trees) Jeremy Morris

Data Structures and Algorithms Lists

LINKED DATA STRUCTURES

D06 PROGRAMMING with JAVA

Chapter 8: Bags and Sets

Data Structures and Algorithms

1. The memory address of the first element of an array is called A. floor address B. foundation addressc. first address D.

Generic Types in Java. Example. Another Example. Type Casting. An Aside: Autoboxing 4/16/2013 GENERIC TYPES AND THE JAVA COLLECTIONS FRAMEWORK.

Analysis of a Search Algorithm

Java Collection Framework hierarchy. What is Data Structure? Chapter 20 Lists, Stacks, Queues, and Priority Queues

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

Java Map and Set collections

Basic Programming and PC Skills: Basic Programming and PC Skills:

Ordered Lists and Binary Trees

Useful Java Collections

AP Computer Science Java Mr. Clausen Program 9A, 9B

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Java Collections -- List Set Map

22c:31 Algorithms. Ch3: Data Structures. Hantao Zhang Computer Science Department

A binary search tree or BST is a binary tree that is either empty or in which the data element of each node has a key, and:

Abstract Data Type. EECS 281: Data Structures and Algorithms. The Foundation: Data Structures and Abstract Data Types

1 of 1 24/05/ :23 AM

DATA STRUCTURE - STACK

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

CSE373: Data Structures and Algorithms Lecture 1: Introduction; ADTs; Stacks/Queues. Linda Shapiro Spring 2016

Last not not Last Last Next! Next! Line Line Forms Forms Here Here Last In, First Out Last In, First Out not Last Next! Call stack: Worst line ever!

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Introduction to Data Structures

Principles of Software Construction: Objects, Design and Concurrency. Java Collections. toad Fall 2013

1.00 Lecture 35. Data Structures: Introduction Stacks, Queues. Reading for next time: Big Java: Data Structures

Big O and Limits Abstract Data Types Data Structure Grand Tour.

CS104: Data Structures and Object-Oriented Design (Fall 2013) October 24, 2013: Priority Queues Scribes: CS 104 Teaching Team

Krishna Institute of Engineering & Technology, Ghaziabad Department of Computer Application MCA-213 : DATA STRUCTURES USING C

Lecture 2: Data Structures Steven Skiena. skiena

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

CMSC 202H. ArrayList, Multidimensional Arrays

Chapter 3: Restricted Structures Page 1

Glossary of Object Oriented Terms

Sequential Data Structures

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

1) The postfix expression for the infix expression A+B*(C+D)/F+D*E is ABCD+*F/DE*++

Java Coding Practices for Improved Application Performance

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

COMPUTER SCIENCE. Paper 1 (THEORY)

7.1 Our Current Model

Data Structures and Algorithms

Programming with Data Structures

Unit Testing & JUnit

Data Structures In Java

CompSci-61B, Data Structures Final Exam

Linked Lists Linked Lists, Queues, and Stacks

Data Structures and Algorithms Written Examination

STORM. Simulation TOol for Real-time Multiprocessor scheduling. Designer Guide V3.3.1 September 2009

Data Structures and Data Manipulation

Sorting revisited. Build the binary search tree: O(n^2) Traverse the binary tree: O(n) Total: O(n^2) + O(n) = O(n^2)

HW3: Programming with stacks

Génie Logiciel et Gestion de Projets. Refactoring

Structural Design Patterns Used in Data Structures Implementation

Binary Heaps * * * * * * * / / \ / \ / \ / \ / \ * * * * * * * * * * * / / \ / \ / / \ / \ * * * * * * * * * *

Java Software Structures

Software Engineering Techniques

MAX = 5 Current = 0 'This will declare an array with 5 elements. Inserting a Value onto the Stack (Push)

This lecture. Abstract data types Stacks Queues. ADTs, Stacks, Queues Goodrich, Tamassia

Introduction: Abstract Data Types and Java Review

ADTs,, Arrays, Linked Lists

The ADT Binary Search Tree

Class Overview. CSE 326: Data Structures. Goals. Goals. Data Structures. Goals. Introduction

Data Structures. Level 6 C Module Descriptor

Stacks. Data Structures and Data Types. Collections

A DESIGN PATTERNS PERSPECTIVE ON DATA STRUCTURES. Virginia Niculescu

Linked Lists, Stacks, Queues, Deques. It s time for a chainge!

Chapter 14 The Binary Search Tree

Iterators. Provides a way to access elements of an aggregate object sequentially without exposing its underlying representation.

Contents. 9-1 Copyright (c) N. Afshartous

cs2010: algorithms and data structures

Financial Management System

CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Keys and records. Binary Search Trees. Data structures for storing data. Example. Motivation. Binary Search Trees

CHAPTER 4 ESSENTIAL DATA STRUCTRURES

Refactoring for Parameterizing Java Classes

Algorithms and Data Structures Written Exam Proposed SOLUTION

Queues Outline and Required Reading: Queues ( 4.2 except 4.2.4) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Computer Programming I

PES Institute of Technology-BSC QUESTION BANK

10CS35: Data Structures Using C

Software Development. Chapter 7. Outline The Waterfall Model RISKS. Java By Abstraction Chapter 7

Transcription:

Java's Collection Framework 1

Java's Collection Framework w w w Collection framework Unified architecture for representing and manipulating collections Java's collection framework contains Interfaces (ADTs): specification not implementation Concrete implementations as classes Polymorphic Algorithms to search, sort, find, shuffle,... The algorithms are polymorphic: the same method can be used on many different implementations of the appropriate collection interface. In essence, algorithms are reusable functionality. 2

Collection interfaces in java.util Image from the Java Tutorial 3

Abstract Data Type wabstract data type (ADT) is a specification of the behaviour (methods) of a type Specifies method names to add, remove, find Specifies if elements are unique, indexed, accessible from only one location, mapped,... An ADT shows no implementation no structure to store elements, no implementations w Which Java construct nicely specifies ADTs? 4

Collection Classes wa collection class the can be instantiated implements an interface as a Java class implements all methods of the interface selects appropriate instance variables w Java has many collection classes including: ArrayList<E> LinkedList<E> LinkedBlockingQueue<E> ArrayBlockingQueue<E> Stack<E> HashSet<E> TreeSet<E> HashMap<K,V> TreeMap<K,V> 5

Common Functionality w Collection classes often have methods for Adding objects Removing an object Finding a reference to a particular object We can then send messages to the object still referenced by the collection 6

The Collection Interface w interface Collection abstractly describes a bag, or multi-set wsome classes implementing Collection allow duplicate elements; others do not keeps elements ordered; others do not 7

Collection method signatures wthe methods of interface Collection http://java.sun.com/javase/7/docs/api/java/util/collection.html boolean add(e e) boolean addall(collection<? extends E> c) void clear() boolean contains(object o) boolean containsall(collection<?> c) boolean equals(object o) int hashcode() boolean isempty() Iterator<E> iterator() boolean remove(object o) boolean removeall(collection<?> c) boolean retainall(collection<?> c) int size() Object[] toarray() 8

Why have interface Collection? w Collection allows different types of objects to be treated the same wit is used to pass around collections of objects with maximum generality for example addall(collection<? extends E> c) This method adds all of the elements in the specified collection in an appropriate way Can add all elements of a List to a Queue, or add all elements of a Set to a List, or add all elements of one List to another List 9

Why have interface Collection? wwith this method, we can iterate over all Collections using hasnext and Next Iterator<E> iterator() wwith this method, we can find out if all the elements in a set are in a list or queue, or boolean containsall(collection<?> c) 10

interface List extends interface Collection wlist: a collection where indexes matter extends Collection so it has all of the methods of Collection Can decide where in the List elements are inserted 11

List<E>, an Abstract Data Type (ADT) written as a Java interface w List<E>: a collection with a first element, a last element, distinct predecessors and successors The user of this interface has precise control over where in the list each element is inserted duplicates that "equals" each other are allowed 12

List<E> w Users of the interface List<E> have precise control over where in the list each element is inserted. allows programmers to access elements by their integer index (position in the list) search for elements in the list Can have duplicate elements (equals) Methods include: add, addall, indexof, isempty, remove, toarray w Some implementing classes in java.util: ArrayList<E>, LinkedList<E>, Stack<E>, Vector<E>, many more 13

import java.util.*; // For List, ArrayList, Linked... import static org.junit.assert.*; import org.junit.test; public class ThreeClassesImplementList { @Test public void showthreeimplementationsoflist() { // Interface name: List // Three classes that implement the List interface: List<String> alist = new ArrayList<String>(); List<String> ellist = new LinkedList<String>(); List<String> sharedlist = new Vector<String>(); // All three have an add method alist.add("in array list"); ellist.add("in linked list"); sharedlist.add("in vector"); } } // All three have a get method assertequals("in array list", alist.get(0)); assertequals("in linked list", ellist.get(0)); assertequals("in vector", sharedlist.get(0)); 14

Iterate over different lists the same way List<Integer> arrayl = new ArrayList<Integer>(); List<Integer> linkedl = new LinkedList<Integer>(); for (int num = 1; num <= 12; num += 2) { arrayl.add(num); linkedl.add(num + 1); } Iterator<Integer> arrayitr = arrayl.iterator(); Iterator<Integer> linkeditr = linkedl.iterator(); while (arrayitr.hasnext()) System.out.print(arrayItr.next() + " "); System.out.println(); while (linkeditr.hasnext()) System.out.print(linkedItr.next() + " "); Output: 1 3 5 7 9 11 2 4 6 8 10 12 15

The enhanced for loop List<Integer> arrayl = new ArrayList<Integer>(); List<Integer> linkedl = new LinkedList<Integer>(); for (int num = 1; num <= 12; num += 2) { arrayl.add(num); linkedl.add(num + 1); } for (Integer theint : arrayl) System.out.print(theInt + " "); System.out.println(); for (Integer theint : linkedl) System.out.print(theInt + " "); Output is the same, no iterators needed: 1 3 5 7 9 11 2 4 6 8 10 12 16

Polymorphism via interfaces wthe previous slides shows different types treated as type List, all three implement interface List understand the same messages have different methods with the same names execute All classes have add, get, iterator w This is polymorphism via interfaces 17

Queue<E> boolean add(e e) Inserts e into this queue E element() Retrieves, but does not remove, the head of this queue boolean offer(e e)inserts e into this queue E peek() Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty E poll() Retrieves and removes the head of this queue, or returns null if this queue is empty E remove() Retrieves and removes the head of this queue 18

ArrayBlockingQueue<E> a FIFO queue ArrayBlockingQueue<Double> numberq = new ArrayBlockingQueue<Double>(40); numberq.add(3.3); numberq.add(2.2); numberq.add(5.5); numberq.add(4.4); numberq.add(7.7); assertequals(3.3, numberq.peek(), 0.1); assertequals(3.3, numberq.remove(), 0.1); assertequals(2.2, numberq.remove(), 0.1); assertequals(5.5, numberq.peek(), 0.1); assertequals(3, numberq.size()); 19

TreeSet implements Set w Set<E> An interface for collections with no duplicates. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2) w TreeSet<E>: This class implements the Set interface, backed by a balanced binary search tree. This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements as defined by Comparable<T> 20

TreeSet elements are in order SortedSet<Integer> set = new TreeSet<Integer>(); set.add(7); set.add(7); set.add(2); set.add(7); set.add(8); set.add(9); System.out.println(set.toString()); System.out.println(set.subSet(1, 8)); System.out.println(set.tailSet(8)); System.out.println(set.headSet(8)); [2, 7, 8, 9] [2, 7] [8, 9] [2, 7] 21

HashSet elements are not in order Set<String> names = new HashSet<String>(); names.add("devon"); names.add("sandeep"); names.add("chris"); names.add("kim"); names.add("chris"); // not added for (String str : names) System.out.print(str + " "); Output: Sandeep Chris Devon Kim 22

The Map Interface (ADT) wmap describes a type that stores a collection of elements that consists of a key and a value w A Map associates (maps) a key the it's value wthe keys must be unique the values need not be unique put destroys one with same key w Concrete classes in java.util HashMap<K, V> and TreeMap<K, V> 23

Map Operations w java.util.hashmap<k,v> public V put(k key, V value) associates key to value and stores mapping public V get(k key) associates the value to which key is mapped or null public boolean containskey(k key) returns true if the Map already uses the key public V remove(k key) public Collection<V> values() get a collection you can iterate over public Collection<V> keyset() get a collection you can iterate over 24

Using a Map Map<String, BankAccount> amap= new TreeMap<String, BankAccount>(); BankAccount acct1 = new BankAccount("Jessica", 500.00); BankAccount acct2 = new BankAccount("Alex", 400.00); BankAccount acct3 = new BankAccount("Anthony", 300.00); BankAccount acct4 = new BankAccount("Danny", 200.00); amap.put(acct1.getid(), acct1); amap.put(acct2.getid(), acct2); amap.put(acct3.getid(), acct3); amap.put(acct4.getid(), acct4); // Check out the keys and the value in amap Collection<String> keys = amap.keyset(); System.out.println(keys); Collection<BankAccount> values = amap.values(); System.out.println(values); Output [Alex, Anthony, Danny, Jessica] [Alex $400.0, Anthony $300.0, Danny $200.0, Jessica $500.0] 25

Using a Map // over write a value, put returns old value System.out.println(aMap.put("Jessica", new BankAccount("New", 0.99))); Output Jessica $500.00 // put in a new key, get null back System.out.println(aMap.put("NewKey", new BankAccount("NewValue", 0))); Output null // successful remove return the removed value System.out.println(aMap.remove("Jessica")); Output New $0.99 26