Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java's Collection Framework

Similar presentations


Presentation on theme: "Java's Collection Framework"— Presentation transcript:

1 Java's Collection Framework

2 Java's 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.

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

4 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?

5 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>

6 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

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

8 Collection method signatures
The methods of interface Collection 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?
Collection allows different types of objects to be treated the same It 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

10 Why have interface Collection?
With this method, we can iterate over all Collections using hasNext and Next Iterator<E> iterator() With 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
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

12 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

13 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>, many more

14 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)); }

15 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:

16 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) Output is the same, no iterators needed:

17 Polymorphism via interfaces
The 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 This 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
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>

21 TreeSet elements are in order
SortedSet<Integer> set = new TreeSet<Integer>(); set.add(7); set.add(2); 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]

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)
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 put destroys one with same key Concrete classes in java.util HashMap<K, V> and TreeMap<K, V>

24 Map Operations 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()

25 Using a Map Map<String, BankAccount> aMap= new TreeMap<String, BankAccount>(); BankAccount acct1 = new BankAccount("Jessica", ); BankAccount acct2 = new BankAccount("Alex", ); BankAccount acct3 = new BankAccount("Anthony", ); BankAccount acct4 = new BankAccount("Danny", ); 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]

26 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))); null // successful remove return the removed value System.out.println(aMap.remove("Jessica")); New $0.99


Download ppt "Java's Collection Framework"

Similar presentations


Ads by Google