java's collection framework - university of arizona · 2016. 4. 26. · 2 java's...
TRANSCRIPT
1
Java's Collection Framework
2
Java's Collection Framework
w Collection framework— Unified architecture for representing and manipulating
collectionsw Java's collection framework contains
— Interfaces (ADTs): specification not implementation— Concrete implementations as classes— Polymorphic Algorithms to search, sort, find, shuffle, ...
w 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.
3
Collection interfaces in java.util
Image from the Java Tutorial
4
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
wWhich Java construct nicely specifies ADTs?
5
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
wJava 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>
6
Common Functionality
wCollection 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
7
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
8
Collection method signatures
wThe methods of interface Collectionhttp://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()
9
Why have interface Collection?
w Collection allows different types of objects to be treated the same
w It is used to pass around collections of objects with maximum generality for exampleaddAll(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
10
Why have interface Collection?
wWith this method, we can iterate over all Collections using hasNext and NextIterator<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)
11
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
12
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
13
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
14
import java.util.*; // For List, ArrayList, Linked ... import static org.junit.Assert.*;import org.junit.Test;
public class ThreeClassesImplementList {
@Testpublic 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 methodaList.add("in array list");elList.add("in linked list");sharedList.add("in vector");
// All three have a get methodassertEquals("in array list", aList.get(0));assertEquals("in linked list", elList.get(0));assertEquals("in vector", sharedList.get(0));
}}
15
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
Iterate over different lists the same way
16
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
The enhanced for loop
17
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
wThis is polymorphism via interfaces
18
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
19
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());
20
TreeSet implements Set
wSet<E> An interface for collections with no duplicates. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)
wTreeSet<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>
21
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]
22
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
23
The Map Interface (ADT)
wMap describes a type that stores a collection of elements that consists of a key and a value
wA Map associates (maps) a key the it's valuewThe keys must be unique
— the values need not be unique— put destroys one with same key
wConcrete classes in java.util— HashMap<K, V> and TreeMap<K, V>
24
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
25
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 aMapCollection<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]
26
Using a Map
// over write a value, put returns old valueSystem.out.println(aMap.put("Jessica", new BankAccount("New", 0.99)));
OutputJessica $500.00
// put in a new key, get null backSystem.out.println(aMap.put("NewKey", new BankAccount("NewValue", 0)));
Outputnull
// successful remove return the removed valueSystem.out.println(aMap.remove("Jessica"));
OutputNew $0.99