Java Collection
Framework
Collection Framework
A collection framework is a unified architecture for
representing and manipulating collections. It has:
– Interfaces: abstract data types representing
collections
– Implementations: concrete implementations of
the collection interfaces
– Algorithms: methods that perform useful
computations, such as searching and sorting
• These algorithms are said to be polymorphic:
the same method can be used on different
implementations
Collection interfaces
Queue
Collection Interface continued
• Set →
The familiar set abstraction.
No duplicates; May or may not be ordered.
• List →
Ordered collection, also known as a sequence.
Duplicates permitted; Allows positional access
• Map →
A mapping from keys to values.
Each key can map to at most one value (function).
The keys are like indexes. In List, the indexes are
integer. In Map, the keys can be any objects.
• Queue →
Ordered collection. FIFO (First In First Out)
Type Trees for Collections
Iterable<E> Iterator<E>
Collection<E> ListIerator<E>
Set<E> Queue<E> List<E>
SortedSet<E> EnumSet<E> ArrayList<E>
PriorityQueue<E>
HashSet<E> LinkedList<E>
TreeSet<E>
LinkedHashSet<E>
Map<K,V>
EnumMap<K,V>
WeakHashMap<K,V>
SortedMap<K,V>
HashMap<E>
TreeMap<K,V>
LinkedHashMap<K,V>
6
Java Collection Framework hierarchy,
cont.
Set and List are subinterfaces of Collection.
SortedSet TreeSet
Set AbstractSet HashSet LinkedHashSet
Collection AbstractCollection
Vector Stack
List AbstractList
ArrayList
AbstractSequentialList LinkedList
Deque
Queue AbstractQueue PriorityQueue
Interfaces Abstract Classes Concrete Classes
Collections Framework Diagram
7
Collection Interface
• Defines fundamental methods
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(Object element); // Optional
boolean remove(Object element); // Optional
Iterator iterator();
• These methods are enough to define the basic
behavior of a collection
• Provides an Iterator to step through the elements in
the Collection
8
Interface Collection
•add(o) Add a new element
• addAll(c) Add a collection
•clear() Remove all elements
•contains(o) Membership checking.
•containsAll(c) Inclusion checking
•isEmpty() Whether it is empty
•iterator() Return an iterator
•remove(o) Remove an element
•removeAll(c) Remove a collection
•retainAll(c) Keep the elements
•size() The number of elements
Iterator Interface
• Defines three fundamental methods
Object next()
boolean hasNext()
void remove()
• These three methods provide access to the
contents of the collection
• An Iterator knows position within collection
• Each call to next() “reads” an element from the
collection
Then you can use it or remove it
10
Iterator Position
11
Example - SimpleCollection
public class SimpleCollection {
public static void main(String[] args) {
Collection c;
c = new ArrayList();
[Link]([Link]().getName());
for (int i=1; i <= 10; i++) {
[Link](i + " * " + i + " = "+i*i);
}
Iterator iter = [Link]();
while ([Link]())
[Link]([Link]());
}} 12
List Interface Context
Collection
List
13
List Interface
• The List interface adds the notion of
order to a collection
• The user of a list has control over where
an element is added in the collection
• Lists typically allow duplicate elements
• Provides a ListIterator to step through the
elements in the list.
14
ListIterator Interface
• Extends the Iterator interface
• Defines three fundamental methods
void add(Object o) - before current position
boolean hasPrevious()
Object previous()
• The addition of these three methods defines
the basic behavior of an ordered list
• A ListIterator knows position within list
15
Iterator Position - next(), previous()
16
ArrayList and LinkedList Context
Collection
List
ArrayList LinkedList
17
List Implementations
• ArrayList
low cost random access
high cost insert and delete
array that resizes if need be
• LinkedList
sequential access
low cost insert and delete
high cost random access
18
ArrayList overview
• Constant time positional access (it’s an array)
• One tuning parameter, the initial capacity
public ArrayList(int initialCapacity) {
super();
if (initialCapacity < 0)
throw new IllegalArgumentException(
"Illegal Capacity: "+initialCapacity);
[Link] = new Object[initialCapacity];
}
19
ArrayList methods
• The indexed get and set methods of the List
interface are appropriate to use since ArrayLists
are backed by an array
Object get(int index)
Object set(int index, Object element)
• Indexed add and remove are provided, but can be
costly if used frequently
void add(int index, Object element)
Object remove(int index)
• May want to resize in one shot if adding many
elements
void ensureCapacity(int minCapacity) 20
LinkedList overview
• Stores each element in a node
• Each node stores a link to the next and
previous nodes
• Insertion and removal are inexpensive
just update the links in the surrounding nodes
• Linear traversal is inexpensive
• Random access is expensive
Start from beginning or end and traverse each
node while counting
21
LinkedList methods
• The list is sequential, so access it that way
ListIterator listIterator()
• ListIterator knows about position
use add() from ListIterator to add at a position
use remove() from ListIterator to remove at a position
• LinkedList knows a few things too
void addFirst(Object o), void addLast(Object o)
Object getFirst(), Object getLast()
Object removeFirst(), Object removeLast()
22
Set Interface Context
Collection
Set
23
Set Interface
• Same methods as Collection
different contract - no duplicate entries
• Defines two fundamental methods
boolean add(Object o) - reject duplicates
Iterator iterator()
• Provides an Iterator to step through the elements
in the Set
No guaranteed order in the basic Set interface
There is a SortedSet interface that extends Set
24
HashSet and TreeSet Context
Collection
Set
HashSet TreeSet
25
HashSet
• Find and add elements very quickly
uses hashing implementation in HashMap
• Hashing uses an array of linked lists
The hashCode() is used to index into the array
Then equals() is used to determine if element is in
the (short) list of elements at that index
• No order imposed on elements
• The hashCode() method and the equals() method
must be compatible
if two objects are equal, they must have the same
hashCode() value
26
TreeSet
• Elements can be inserted in any order
• The TreeSet stores them in order
• An iterator always presents them in order
• Default order is defined by natural order
objects implement the Comparable interface
TreeSet uses compareTo(Object o) to sort
27
Map Interface Context
Map
28
Map Interface
• Stores key/value pairs
• Maps from the key to the value
• Keys are unique
a single key only appears once in the
Map
a key can map to only one value
• Values do not have to be unique
29
Map methods
Object put(Object key, Object value)
Object get(Object key)
Object remove(Object key)
boolean containsKey(Object key)
boolean containsValue(Object value)
int size()
boolean isEmpty()
30