Professional Documents
Culture Documents
1
Collections
Iterators (1)
2
Iterators (2)
Iterators (3)
Lists can be traversed in both directions, and a new interface
is defined for this special case:
3
Collections Framework in Java 5
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
Sets: Interfaces(1)
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
8
Sets: <<concrete>> classes (2)
9
The interface for lists (1)
10
Abstract classes for Lists(1)
11
Class Vector (1)
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
Class LinkedList(1)
13
Class LinkedList (2)
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
Map interface
15
Interface SortedMap
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
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();
}
…
}
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)
Arrays class
19