Lecture 6
Lecture 6
Collections
Concept
A collection is a data structure – actually, an object – to hold other
objects, which let you store and organize objects in useful ways for
efficient access
Check out the java.util package! Lots of interfaces and classes
providing a general collection framework. Programmers may also
provide implementations specific to their own requirements
Overview of the interfaces and concrete classes in the collection
framework
Collection Map Iterator
HashMap
Set List SortedMap ListIterator
WeakHashMap
1
Root interface – Collection (1)
Methods working with an individual collection
public int size()
public boolean isEmpty()
public boolean contains(Object elem)
public boolean add(Object elem)
Depends on whether the collection allows duplicates
public boolean remove(Object elem)
public boolean equals(Object o)
public int hashCode()
public Iterator iterator()
public Object[] toArray()
Returns a new array containing references to all the elements of the
collection
public Object[] toArray(Object[] dest)
What is returned depends on whether the elements in the collection fit in
dest
If the type of dest is not compatible with the types of all elements in the
collection, an exception is thrown
2
Iteration - Iterator
The Collection interface defines an iterator method to
return an object implementing the Iterator interface.
It can access the elements in a collection without exposing its internal
structure.
There are NO guarantees concerning the order in which the elements
are returned
Three defined methods in Iterator interface
public boolean hasNext() – returns true if the iteration has more
elements
public Object next() – returns the next element in the iteration
An exception will be thrown if there is no next element
What’s returned is an Object object. You may need special casting!
public void remove() – remove from the collection the element
last returned by the iteration
can be called only once per call of next, otherwise an exception is
thrown
3
Iteration - ListIterator
ListerIterator interface extends Iterator interface. It adds
methods to manipulate an ordered List object during iteration
Methods
public boolean hasNext()/ public boolean hasPrevious()
public Object next()/ public Object previous()
public Object nextIndex()/ public Object previousIndex()
When it’s at the end of the list, nextIndex() will return list.size()
When it’s at the beginning of the list, previousIndex() will return -1
public void remove() – remove the element last returned by next() or
previous()
public void add(Object o)– insert the object o into the list in front of the
next element that would be returned by next(), or at the end if no next
element exists
public void set(Object o) – set the element last returned by next() or
previous() with o
4
Potential problem of Iterator/ListIterator (cont.)
A snapshot will return the elements as they were when the
Iterator/ListIterator object was created, which is
unchangeable in the future
If you really need a snapshot, you can make a simple copy of the
collection
Many of the iterators defined in the java.util package are in
the type of fail-fast iterators
They detect when a collection has been modified
When a modification is detected, other than risk performing an
action whose behavior may be unsafe, they fail quickly and cleanly
by throwing an exception –
ConcurrentModificationException
import java.util.*;
public class IteratorTest2 {
public static void main (String args[]) {
ArrayList a = new ArrayList();
a.add(“1”);
a.add(“2”);
a.add(“3”);
Iterator it = a.iterator();
a.add(“4”);
while(it.hasNext()) {
String s = (String)(it.next());
System.out.println(s);
}
}
}
5
List
A List is an ordered Collection which allows duplicate
elements. Its element indices range from 0 to
(list.size()-1)
It adds several methods for an ordered collection
The interface List is implemented by two classes
1. ArrayList: a resizable-array implementation of the List
interface
Adding or removing elements at the end, or getting an element at a specific
position is simple – O(1)
Adding or removing element from the middle is more expensive – O(n-i)
Can be efficiently scanned by using the indices without creating an
Iterator object, so it’s good for a list which will be scanned frequently
2. LinkedList: a doubly-linked list
Getting an element at position i is more expensive – O(i)
A good base for lists where most of the actions are not at the end
6
Map and SortedMap
The Map interface does not extend Collection interface because
a Map contains key-value pairs, not only keys. Duplicate keys are
not allowed in a Map. It’s implemented by classes HashMap and
TreeMap.
There are methods to view the map using collections. For example:
public Set keySet() and public Collection values().
The collections returned by these methods are backed by the Map, so
removing an element from one these collections removes the
corresponding key/value pair from the map
You cannot add elements to these collections
If you iterate through the key or value sets, they may return values from
their respective sets in any order
Interface SortedMap extends Map and maintains its keys in sorted
order. Class TreeMap implements SortedMap.
An example using HashMap (output)
7
Synchronized wrappers and the Collections class (2)
The above methods return wrappers whose methods are fully
synchronized, and so are safe to use from multiple threads
Example
Map unSyncMap = new HashMap();
Map syncMap = Collections.synchronizedMap(unSyncMap);
synchronized
wrapper
syncMap
8
Unmodifiable wrappers and the Collections class (2)
Example
Original: it’s dangerous that the array’s content can be changed
public String suits[]= {
“Hearts”, “Clubs”, “Diamonds”, “Spades” };
Using the unmodifiable wrapper to prevent the danger:
private String suitsNames[] = {
“Hearts”, “Clubs”, “Diamonds”, “Spades” };
public final List suits =
Collections.unmodifiableList(Arrays.asList(suitNames
);
Abstract implementations
9
The legacy collection types
10