You are on page 1of 19

Topic XX

Collections Framework in Java 5


DAAD project
“Joint Course on OOP using
Java”
Humboldt University Berlin, University of Novi Sad, ‘Polytehnica’ University of Timisoara,
University of Plovdiv, University of Belgrade

Version: September 1, 2004

Collections Framework in Java 5

a) Collections Framework and Iterators


b) Collection interface
c) Sets
d) Lists and Queues
e) Maps
f) Collections and Arrays classes

DAAD project „Joint Course on OOP using Java“ © 2

1
Collections

Collections: classes that store and manage


groups of objects (aka containers)
Collection framework: group of interfaces
and classes in package java.util for
working with:
• Sets
• Sequences (lists, queues)
• Maps
Important property: automatic extension of
size, to accomodate as many objects as
required
DAAD project „Joint Course on OOP using Java“ © 3

Iterators (1)

Common operation: visiting/retrieval of all


objects in a collection (iteration)
Iterator: an object containing references to
all objects in a collection
Interface Iterator in package java.util:
public interface Iterator <E> {
boolean hasNext();
E next()
void remove();
}

DAAD project „Joint Course on OOP using Java“ © 4

2
Iterators (2)

Any class that uses iteration must


implement the Iterator<> interface and
provide a method that returns an iterator.
Important: a new iterator is required for
each iteration operation.
The method for returning an iterator is
specified in a separate interface, Iterable:
public interface Iterable {
Iterator<T> iterator();
}

DAAD project „Joint Course on OOP using Java“ © 5

Iterators (3)
 Lists can be traversed in both directions, and a new interface
is defined for this special case:

public interface ListIterator extends Iterator{


boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void add(E o);
void set(E o);
}
 add inserts immediately before the element to be returned by
next call to next()
 set replaces the last object returned by next() or
previous()

DAAD project „Joint Course on OOP using Java“ © 6

3
Collections Framework in Java 5

a) Collections Framework and Iterators


b) Collection interface
c) Sets
d) Lists and Queues
e) Maps
f) Collections and Arrays classes

DAAD project „Joint Course on OOP using Java“ © 7

Collection interface (1)

 There are 5 interfaces for sequences and 2 for


maps in the java.util package

DAAD project „Joint Course on OOP using Java“ © 8

4
Collection interface(2)
public interface Collection<E>extends Iterable<E> {
boolean add(E o);
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 retainsAll(Collection<?> c);
int size();
Object[ ] toArray();
<T> t[ ] toArray(T[ ] a);
}
DAAD project „Joint Course on OOP using Java“ © 9

Collection interface(3)
 The ‘distructive’ methods (add, addAll, clear,
remove, removeAll, retainAll) are optional, in
the sense that they should not be implemented in
all classes that implement Collection
 Calls to non-implemented methods will generate
UnsupportedOperationException
 Implementations of equals and hashCode must
satisfy:
c1.equals(c2) =>c1.hashCode()==c2.hashCode()
 The toArray methods are a bridge between
collections and arrays, the last method also
controlls the type of the returned array
 There is an abstact class that implements
Collection, with size() and iterator() as
abstract methods: AbstractCollection
DAAD project „Joint Course on OOP using Java“ © 10

5
Collections Framework in Java 5

a) Collections Framework and Iterators


b) Collection interface
c) Sets
d) Lists and Queues
e) Maps
f) Collections and Arrays classes

DAAD project „Joint Course on OOP using Java“ © 11

Sets: Interfaces(1)

The Set interface has no new methods, but


imposes restrictions on some of the
Collection methods:
• For equals:
s1.equals(s2) returns true iff s2 is a set, and s1
and s2 have the same size, and each member of
s2 is contained in s1
• For hashCode: the hash code of a set is the
sum of the hash codes of all members
• For add: the element is not added if already
present in the set (sets do not allow duplicates)
A Set cannot contain itself as an element
DAAD project „Joint Course on OOP using Java“ © 12

6
Sets: Interfaces(2)
 A Set can be sorted, such that an iterator traverses it in the
natural order (Comparable)of the members, or the order
given by a Comparator
 Comparable interface (part of java.lang):
public interface Comparable<T>{
int compareTo( T o);
}
 Comparable is implemented in many standard classes,
including wrapper classes, String, Calendar, Date, Time.
 Comparator interface (part of java.util ):
public interface Comparator<T> {
int compare (T o1, T o2);
boolean equals(Object obj);
}
 The order imposed by Comparable and Comparator must be
compatible with equality, i.e.
e1.compareTo(e2)==0 has the same boolean value as
e1.equals((Object)e2).
DAAD project „Joint Course on OOP using Java“ © 13

Sets: interfaces(3)
 Implementations of compare() must ensure transitivity:
((compare(x,y)>0) && (compare(y,z)>0))
=>compare(x,z)>0
 equals is redefined to emphasize that the parameter must
also be a Comparator with the same order as the current
object
 Sorted sets must implement the interface:
public interface SortedSet<E>extends Set<E> {
Comparator<? super E>comparator();
E first();
E last();
SortedSet<E> headSet(E toElement);
SortedSet<E> subSet(E fromElement, E toElement);
SortedSet<E> tailSet (E fromElement);
}
 The last 3 methods return views of the original set, thus any
change in the original set is immediately reflected in the
subset
DAAD project „Joint Course on OOP using Java“ © 14

7
Sets: abstract class

 java.util contains an abstract class which


implements Set:
public abstract class AbstractSet<E> extends
AbstractCollection<E>implements Set<E>
 This class does not override the
AbstractCollection methods, except for
removeAll,and it adds implementations for equals
and hashCode of class Object, according to the
requirements of Set.
 AbstractSet has a protected constructor, to be
used by classes derived from it

DAAD project „Joint Course on OOP using Java“ © 15

Sets: « concrete » classes (1)


 java.util provides the following classes for sets, lists and queues:

DAAD project „Joint Course on OOP using Java“ © 16

8
Sets: <<concrete>> classes (2)

 TreeSet, HashSet and LinkedHashSet are backed by Maps,


and will be presented later
 EnumSet is, in fact, an abstract class:
public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>
implements Cloneable, Serializable
 All elements of an EnumSet must come from a single Enum
type
 Very efficient internal representation, as a bit vector
 All the basic operations execute in constant time
 Type-safe alternative to traditional int-based « bit flags »
 null elements not permitted
 Non-synchronized, like most concrete classes of the
collections framework

DAAD project „Joint Course on OOP using Java“ © 17

Collections Framework in Java 5

a) Collections Framework and Iterators


b) Collection interface
c) Sets
d) Lists and Queues
e) Maps
f) Collections and Arrays classes

DAAD project „Joint Course on OOP using Java“ © 18

9
The interface for lists (1)

 Unlike Sets, lists allow duplicate elements


 There is an exact control on the position of elements
 There are restrictions on contracts of methods inherited from
Collection, and new methods
 The List interface (only new methods shown):
public interface List<E> extends Collection<E> {
void add (int index, E element);
boolean addAll(int index, Collection<? extends E> c);
E get (int index);
int indexOf (Object o);
int lastIndexOf (Object o);
ListIterator<E>listIterator();
ListIterator<E> listIterator(int index);
E remove (int index);
E set (int index, E element);
List<E> subList(int fromIndex, int toIndex);
}

DAAD project „Joint Course on OOP using Java“ © 19

The interface for lists (2)


 Inherited addAll adds at the end of current list, in the order
given by the iterator of the specified Collection
 New addAll adds in the specified position, the indexes of
elements after the given index will change
 Inherited remove: deletes the first occurrence of the specified
element
 New remove deletes the element in the specified position
 subList returns a view of the original List
 equals and hashCode are redefined: two lists are equal if
they contain the same elements in the same order; the hash
code of a list is calculated as follows:
hashCode = 1;
Iterator i = list.iterator();
while (i.hasNext()) {
Object obj = i.next();
hashCode = 31*hashCode + (obj==null ? 0 :
obj.hashCode());
}
DAAD project „Joint Course on OOP using Java“ © 20

10
Abstract classes for Lists(1)

 AbstractList provides an implementation of List


backed by a random access data store (e.g. an
array):
public abstract class AbstractList<E>
extends AbstractCollection<E>
implements List<E>
 All methods, except get and size, are
implemented and there is also a protected
constructor
 Derived classes must override set and add in
order have a modifiable and variable-size list
 Iterator methods do not have to be overriden

DAAD project „Joint Course on OOP using Java“ © 21

Abstract classes for lists (2)

 AbstractSequentialList implements List


backed by a sequential acces data store:
public abstract class
AbstractSequentialList<E>
extends AbstractList<E>
 Now the iterator method is fundamental, and
the « random access » methods ( get, set, add,
remove) are implemented on top of it
 The listIterator method is abstract and must be
implemented in derived classes, together with the
methods of the ListIterator interface
 For modifiable lists, set, remove and add must
also be implemented

DAAD project „Joint Course on OOP using Java“ © 22

11
Class Vector (1)

 Was introduced already in JDK 1.0, before defining


collections framework, and retrofitted in Java 2 to
implement List:
public class Vector<E>extends AbstractList
implements List<E>, RandomAccess,
Cloneable, Serializable
 Represents, in fact, an array of objects whose size
can grow and shrink as required
 Tries to optimize memory management with a
field, capacityIncrement; if not specified, the
capacity is doubled when incrementation is
required
 The implementation is synchronized (thread-safe)
 Has new methods: capacity, trimToSize,
ensureCapacity, setSize
DAAD project „Joint Course on OOP using Java“ © 23

Class Vector (2)

 Example: a class modelling a company can use a Vector to store


data about employees:
class Company {
private Vector<Empl> v = new
Vector<Empl>();

public void hire(){
Empl e = new Empl();
int i=0;
if(v.size()==0) v.add(e);
else {
while (i <v.size() &&
e.getName().compareTo(v.elementAt(i).getNume())>0)
i++;
v.add(i,e);
}
}

DAAD project „Joint Course on OOP using Java“ © 24

12
Classes Stack and ArrayList
 Class Stack:
• Declared as follows:
public class Stack<E> extends Vector<E>
• Adds 5 new methods: push, pop, peek (returns the top
element, without removing it from stack), empty, and
search (if an Object is present on stack)
• Implementation is synchronized (‘old’ class)
 Class ArrayList:
• Similar to Vector, but not synchronized
• Declared as follows:
public class ArrayList<E>extends
AbstractList<E>implements List<E>, RandomAcces,
Cloneable, Serializable
• Does not have addElement, capacity,
removeElementAt of Vector, has: trimToSize,
ensureCapacity

DAAD project „Joint Course on OOP using Java“ © 25

Class LinkedList(1)

 Implements double-linked lists, with sequential


access
 Declared as:
public class LinkedList <E>extends
AbstractSequentialList<E>implements
List<E>, Queue<E>, Cloneable, Serializable
 Some operations require more time than on
Vector or ArrayList
 New methods for operations at the head or tail of
list:
• getFirst, getLast (no change in list)
• removeFirst, removeLast
• addFirst, addLast
 Recommended when operations in the ‘middle’ of
the list are frequent (take O(1) time)
 Needs iterators
DAAD project „Joint Course on OOP using Java“ © 26

13
Class LinkedList (2)

Previous example (data about a company’s employees) implemented


with a linked list:
class Company {
private LinkedList<Empl> el = new LinkedList<Empl>();
public void hire(){
Empl e = new Empl();
int i = 0;
Iterator<Empl>iter = el.listIterator();
if (el.size()==0) el.add(e);
else{
while(iter.hasNext() &&
e.getName().compareTo(iter.next().getName())>0)
i++;
el.add(i, e);
}

}

DAAD project „Joint Course on OOP using Java“ © 27

Queues
 Queue interface:
public interface Queue<E> extends Collection<E>
E element();//returns first elem.(no change-
exception)
boolean offer(E o);
E peek();//returns first elem. (no change-null)
E poll();//returns and removes (null when empty)
E remove();//returns and removes (exception)
}
 Class AbstractQueue:
public abstract class AbstractQueue<E> extends
AbstractCollection<E> implements Queue<e>
 Methods not implemented: offer, poll, peek, size,
iterator
 Class PriorityQueue: a queue with natural order of
elements:
public class PriorityQueue<E> extends AbstractQueue<E>
implements Serializable
DAAD project „Joint Course on OOP using Java“ © 28

14
Collections Framework in Java 5

a) Collections Framework and Iterators


b) Collection interface
c) Sets
d) Lists and Queues
e) Maps
f) Collections and Arrays classes

DAAD project „Joint Course on OOP using Java“ © 29

Map interface

 A Map cannot have duplicate keys V get(Object key);


 A Map contains at most one value int hashCode();
associated with a key boolean isEmpty();
 Map interface: Set<K> keySet();
public interface Map<K, V> { V put(K key, V value):
public static interface void putAll(Map<?extends K, ?
Map.Entry<K, V>{ Extends V> t);
boolean equals (Object o); V remove(Object key);
K getKey(); int size();
V getValue(); Collection<V> values();
int hashCode(); }
V setValue(V value);
 Three Collection views: keys, values,
} entries
void clear();  All views are backed by the map
boolean containsKey(Object key);  put: if the map already contains the
boolean containsValue(Object key, the old associated value is replaced
value); with the new
Set<Map.Entry<K,V>>entrySet();  Optional methods: put, putAll,
boolean equals(Object o); clear, remove

DAAD project „Joint Course on OOP using Java“ © 30

15
Interface SortedMap

 Guarantees ascending order of keys (natural order, or given


by Comparator)
 Definition:
public SortedMap<K,V>extends Map<K,V> {
Comparator<? Super K>comparator();
K firstKey();
SortedMap<K, V> headMap(K toKey);
K lastKey();
SortedMap<K,V> subMap(K fromKey, K toKey);
SortedMap<K,V> tailMap (K fromKey);
}
 All partial views are backed by the original map
 headMap: entries with keys strictly less than toKey
 subMap: inludes fromKey, excludes toKey
 tailMap: includes fromKey
DAAD project „Joint Course on OOP using Java“ © 31

Classes for Maps


 General view of the classes provided in the
colections framework for Maps:

DAAD project „Joint Course on OOP using Java“ © 32

16
Class HashMap (1)
 ‘Auxiliary’ classes: Dictionary and Hashtable
 Dictionary: present since JDK1.0, considered obsolete,
used only by Hashtable
 Hashtable declaration:
public class Hashtable<K,V> extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable
 Two important parameters: initial capacity and load factor
(default values: 11 and 0.75)
 In case of ‘bucket collisions’, entries are chained
 Capacity is automatically increased when load factor is
exceeded; involves rehashing
 Abstract class: AbstractMap:
public abstract class AbstractMap<K, V> extends Object
implements Map<K,V>
 For unmodifiable maps: implement entrySet
 For modfiable maps: override put, implement remove of
iterator

DAAD project „Joint Course on OOP using Java“ © 33

Class HashMap (2)


 Declaration of HashMap:
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
 Hash table based implementation of Map
 Provides all optional Map operations, allows null keys
 Roughly equivalent to Hashtable, but unsynchronized and
permits nulls
 Makes no guarantees as to the order of the map
 Provides constant time performance for basic operations:
get, put
 The iterators, like in most other cases are fail-fast:if the map
is structurally modified at any time after the iterator is
created, in any way except through the iterator's own
remove or add methods, the iterator will throw a
ConcurrentModificationException.
 Four constructors: HashMap(), HashMap(int
initialCapacity), HashMap(int initialCapacity, float
loadFactor), HashMap(Map<? extends K, ? extends V>
m)
DAAD project „Joint Course on OOP using Java“ © 34

17
Class HashMap (3)
 Example of use: a phone book, with person names as keys, and file
save/restore operations for the phone book
 Persons are defined in a separate class, provided with an appropriate
hashCode method:
public int hashCode(){
return 13*name.hashCode() + 19*surname.hashCode();
}
 A separate class defines an entry of phone book: person and phone number
 The class PhoneBook:
class PhoneBook implements Serializable {
private HashMap<Pers, PBEntry> pb = new
HashMap<Pers, PBEntry>();

public getEntry(Pers key){
return pb.get(key);
}
public getPhone(Pers key) {
return getEntry(key).getNumber();
}

}

DAAD project „Joint Course on OOP using Java“ © 35

Collections Framework in Java 5

a) Collections Framework and Iterators


b) Collection interface
c) Sets
d) Lists and Queues
e) Maps
f) Collections and Arrays classes

DAAD project „Joint Course on OOP using Java“ © 36

18
Collections class
 Contains only static methods that
operate on or return collections:
• Polymorphic algorithms operating static <T> int binarySearch
on collections (List<? extends Comparable<?
• Wrappers returning a new super T>> list, T key)
collection backed by a specified static <T>Collection<T>
collection synchronizedCollection
• Odds and ends (Collection<T> c) – backed by
 Examples: the specified collection. To
static int guarantee serial access: all access
frequency(Collection<?> c, to the backed collection
Object o) accomplished through the returned
static <T>void fill(List<? super collection
T>list, T obj) Collection c =
Collections.synchronizedColle
static <T>T max(Collection<? ction(myCollection);
extends T>coll, Comparator<?
super T> comp) …
static void reverse(List<?> synchronized(c) {
list) Iterator i = c.iterator();
static while (i.hasNext())
<K,V>Map<K,V>singletonMap(K foo(i.next());
key, V value) }
static <T>void sort(List<T>list,
Comparator<?super T>c)

DAAD project „Joint Course on OOP using Java“ © 37

Arrays class

 Contains static methods for:


• Manipulating arrays (sorting, searching)
• Factory for viewing arrays as lists
 Examples:
public static <T> void sort (T[ ] a,
Comparator<? super T> c)
public static <T> int binarySearch(T[ ] a, T
key, Comparator<? super T> c)
public static boolean deepEquals(Object [ ]
a, Object[ ] a2)- works on nested arrays of
arbitrary level
public static void fill(Object[ ]a, int
fromIndex, int toIndex, Object val)
public static <T> List<T> asList(T …a)-
returns a fixed-size list backed by the array
DAAD project „Joint Course on OOP using Java“ © 38

19

You might also like