Title: Introduce Java's Collection Framework
1Introduce Java's Collection Framework
2Java'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.
3Collection interfaces in java.util
Image from the Java Tutorial
4Abstract 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 implemented
algorithms - What Java construct nicely specifies ADTs?
5Collection 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 these concrete collection classes and
others - ArrayListltEgt LinkedListltEgt
- LinkedBlockingQueueltEgt ArrayBlockingQueueltEgt
- StackltEgt
- HashSetltEgt TreeSetltEgt
- TreeMapltK,Vgt HashMapltK,Vgt
6Common Functionality
- Collection classes often have methods for
- Adding objects
- Removing an object
- Finding a reference to a particular object find
- can then send messages to the object still in the
collection
7The Collection Interface
- Collection represents a group of objects, known
as elements (a bag or multi-set) - Some classes that implement Collection
- allow duplicate elements others do not
- are ordered others are not
- Collection allows different types of objects to
be passed around - Allows generality, many concrete classes can be
treated as a Collection
8Collection methods
- See the methods of interface Collection at
- http//java.sun.com/javase/6/docs/api/java/util/Co
llection.html - boolean add(E e)
- boolean addAll(Collectionlt? extends Egt c)
- void clear()
- boolean contains(Object o)
- boolean containsAll(Collectionlt?gt c)
- boolean equals(Object o)
- int hashCode()
- boolean isEmpty()
- IteratorltEgt iterator()
- boolean remove(Object o)
- boolean removeAll(Collectionlt?gt c)
- boolean retainAll(Collectionlt?gt c)
- int size()
- Object toArray()
- ltTgt T toArray(T a)
9Other InterfacesNote List and Set extend
Collection
- List an ordered collection
- can contain duplicate elements
- Can decide where in the List element are inserted
- Set a collection that cannot contain duplicate
elements (according to equals) - Map maps keys to values
- Maps cannot contain duplicate keys
- Each key maps at most one value
10ListltEgt, an ADT written as a Java interface
- ListltEgt 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
11List
- Users of the interface List have precise control
over where in the list each element is inserted.
The user can access elements by their integer
index (position in the list), and search for
elements in the list. Can have duplicate elements
(equals). Methods add, addAll, indexOf, isEmpty,
remove, toArray - Some implementing classes in java.util
- ArrayList, AttributeList, CopyOnWriteArrayList,
LinkedList, RoleList, RoleUnresolvedList, Stack,
Vector
12- import java.util. // For List, ArrayList,
Linked ... - import static org.junit.Assert.
- import org.junit.Test
- public class ThreeClassesImplementList
- _at_Test
- public void showThreeImplementationsOfList()
- // Interface name List
- // Three classes that implement the List
interface - ListltStringgt bigList new ArrayListltStringgt()
- ListltStringgt littleList new
LinkedListltStringgt() - ListltStringgt sharedList new
VectorltStringgt() - // All three have an add method
- bigList.add("in array list")
- littleList.add("in linked list")
- sharedList.add("in vector")
13Polymorphism via interfaces
- The previous slide shows three different types
treated as a Collection - Al three implement interface Collection
- The previous slide shows three different types
treated as type Collection, All three - implement interface Collection
- have the same method names
- may have different methods execute
- This is an example of polymorphism via interfaces
14Set
- Set An interface that models the mathematical set
abstraction - Classes that implement the Set interface do not
allow duplicate elements as defined by equals - Concrete class in java.util HashSet
- Subinterface SortedSet
- Concrete class in java.util TreeSet
15The 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, TreeMap
16Map Operations
- Java's TreeMapltK, Vgt
- public V put(K key, V value)
- associates key to value and stores mapping
- public V get(Object 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)
- Returns previous value associated with specified
key, or null if there was no mapping for key. - CollectionltVgt values()
- get a collection you can iterate over
17Using a Map
- _at_Test public void testContainsKey()
- MapltString, BankAccountgt m
- new TreeMapltString, BankAccountgt()
- 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) - m.put(acct1.getID(), acct1)
- m.put(acct2.getID(), acct2)
- m.put(acct3.getID(), acct3)
- m.put(acct4.getID(), acct4)
- m.put(acct5.getID(), acct5)
-
- BankAccount current m.get("Jessica")
- assertEquals("Jessica", current.getID())
-
try to get the Map's Iterator No can do
18Iterators?
- import java.util.Collection
- import java.util.Iterator
- import java.util.Vector
- public class A
- public static void main(String args)
- CollectionltStringgt list new
VectorltStringgt() - list.add("first")
- list.add("2nd")
- list.add("3rd")
- list.add("fourth")
- IteratorltStringgt itr list.iterator()
- while (itr.hasNext())
- System.out.print(itr.next() " ")
-
19Iterator Pattern
- Recurring Problem
- You have an aggregate data type. How can you
access the elements sequentially without exposing
its underlying representation? - Solution
- Provide a separate object, an iterator, that can
retain the current position, and go to the next
element.
20IteratorltTgt
- The Collections framework has the IteratorltTgt
interface with 3 methods - boolean hasNext() Is the iterator positioned at
the last element in the aggregate? - Object next() Move to next element and return it
- void remove() Remove the object most recently
returned by next() - The remove() method is optional. If an Iterator
does not support this method, it throws
UnsupportedOperationException - Collection has IteratorltTgt iterator()
21Iterators
- Iterators provide a general way to traverse all
elements in a collection - ArrayListltStringgt list new
ArrayListltStringgt() - list.add("1-FiRsT")
- list.add("2-SeCoND")
- list.add("3-ThIrD")
- IteratorltStringgt itr list.iterator()
- while (itr.hasNext())
- System.out.println(itr.next().toLowerCase())
-
Output 1-first 2-second 3-third
22Enhanced for Loop
- The enhanced for loop can iterate over all
elements in a collection. - It reduces IteratorltTgt errors and syntax
- General form
- for (type element collection)
- // element is the next thing referenced
each time -
- for (String s list)
- System.out.println(s " ")
Demo map methods values, keys, tailMap, headMap
23Algorithms
- 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)
- Composition (e.g. frequency)
- Finding Extreme Values (e.g. max)
- Demo a few with ArrayList
- begin with main method on the next slide
24- import java.util.ArrayList
- import java.util.Collections
- public class A
- public static void main(String args)
- ArrayListltStringgt list new
ArrayListltStringgt() - list.add("G")
- list.add("A")
- list.add("B")
- list.add("D")
- list.add("C")
- list.add("F")
- System.out.println(list)
- Collections.sort(list)
- System.out.println(list)
-
Output G, A, B, D, C, F A, B, C, D, F, G