280 likes | 320 Vues
Java's Collection Framework. Java's Collection Framework. Collection framework Unified architecture for representing and manipulating collections Java's collection framework contains Interfaces (ADTs): specification not implementation Concrete implementations as classes
E N D
Java's Collection Framework • 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.
Collection interfaces in java.util Image from the Java Tutorial
Abstract Data Type • Abstract 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 • Which Java construct nicely specifies ADTs?
Collection Classes • A collection class the can be instantiated • implements an interface as a Java class • implements all methods of the interface • selects appropriate instance variables • 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>
Common Functionality • 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
The Collection Interface • interface Collection abstractly describes a group of elements as a bag or multi-set • Some classes implementing Collection • allow duplicate elements; others do not • keeps elements ordered; others do not • Collection allows different types of objects to be passed around • Allows generality, many concrete classes can be treated as a Collection
Collection method signatures • The 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()
One InterfaceNote: List extends Collection • List: 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
List<E>, an Abstract Data Type (ADT) written as a Java interface • 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
List<E> • 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 • Some implementing classes in java.util: • ArrayList<E>, LinkedList<E>, Stack<E>, Vector<E>
import java.util.*; // For List, ArrayList, Linked ... • importstatic org.junit.Assert.*; • import org.junit.Test; • publicclass ThreeClassesImplementList { • @Test • publicvoid 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)); • } • }
Polymorphism via interfaces • The previous slide shows three different types treated as type List, all three • implement interfaceList • understand the same messages • may have different methods with the same names execute • This is an example of polymorphism via interfaces • All implementing classes have add, get, iterator
Algorithms • Java has polymorphic algorithms to provide functionality for different types of collections • Sorting (e.g. sort) • Shuffling (e.g. shuffle) • Routine Data Manipulation (e.g. reverse, addAll) • Searching (e.g. binarySearch) • Finding Extreme Values (e.g. max) • Static methods in the Collections class • Demo a few of these with ArrayList …
Add max, min, binarySearch, Switch to LinkedList • List<String> names = new ArrayList<String>(); names.add("Kim"); • names.add("Chris"); • names.add("Dakota"); • names.add("Jamie"); • System.out.println(names); • Collections.sort(names); • System.out.println(names); • Collections.reverse(names); • System.out.println(names); • Collections.shuffle(names); • System.out.println(names); • [Kim, Chris, Dakota, Jamie] • [Chris, Dakota, Jamie, Kim] • [Kim, Jamie, Dakota, Chris] • [Jamie, Chris, Dakota, Kim]
Stack<E> • voidpush(E e) Adds e to the top of the stack • booleanisEmpty() Return true if the has no elements • E peek() Retrieves, but does not remove, the element at the top of this queue E pop() Retrieves and removes the element at the top of this stack
Queue<E> • booleanadd(E e) Inserts e into this queue • E element() Retrieves, but does not remove, the head of this queue • booleanoffer(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
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());
TreeSet implements Set • 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) • 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>
Set and SortedSet • The Set<E> interface methods: • add, addAll, remove, size, but no get! • Two classes that implement Set<E> • TreeSet: values stored in order, O(log n) • HashSet: values in a hash table, no order, O(1) • SortedSet extends Set by adding methods E first() E last() SortedSet<E> tailSet(E fromElement), SortedSet<E> headSet(E fromElement) SortedSet<E> subSet(E fromElement, E toElement)
TreeSet elements are in order • SortedSet<Integer> set = newTreeSet<Integer>(); • set.add(7); • set.add(7); • set.add(2); • set.add(7); • set.add(8); • set.add(9); • System.out.println(set); • System.out.println(set.tailSet(8)); • System.out.println(set.headSet(8)); • System.out.println(set.subSet(1, 9)); • [2, 7, 8, 9] • [8, 9] • [2, 7] • [2, 7, 8]
TreeSet elements are in order • Set<String> names = new TreeSet<String>(); • names.add("Sandeep"); • names.add("Chris"); • names.add("Kim"); • names.add("Chris"); // not added • names.add("Devon"); • for (String name : names) • System.out.println(name); • Output? • Change to HashSet
The Map Interface (ADT) • Map describes a type that stores a collection of elements that consists of a key and a value • A Map associates (maps) a key the it's value • The keys must be unique • the values need not be unique • putdestroys one with same key • Concrete classes in java.util • HashMap<K, V> andTreeMap<K, V>
Map Operations • java.util.HashMap<K, V> • publicV put(K key, V value) • associates key to value and stores mapping • publicV get(K key) • associates the value to which key is mapped or null • publicboolean containsKey(K key) • returns true if the Map already uses the key • publicV remove(K key) • publicCollection<V> values() • get a collection you can iterate over • public Collection<V> keySet() • get a collection you can iterate over
Using a MapTreeMap<K, V> is like our OrderedMap<K, V> • 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); • BankAccount acct5 = new BankAccount("Patrick", 100.00); • aMap.put(acct1.getID(), acct1); • aMap.put(acct2.getID(), acct2); • aMap.put(acct3.getID(), acct3); • aMap.put(acct4.getID(), acct4); • aMap.put(acct5.getID(), acct5); • // 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);