Java Collections
Java Collections
Framework)
Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com
Disclaimer & Acknowledgments
• Even though Sang Shin is a full-time employee of
Sun Microsystems, the contents here are created as
his own personal endeavor and thus does not
necessarily reflect any official stance of Sun
Microsystems on any particular technology
• Acknowledgments
> The contents of this presentation was created from The Java
Tutorials in java.sun.com
2
Topics
3
What is a Collection?
5
What is a Collection Framework?
6
Benefits of Collection Framework
10
Types of Implementations
• General-purpose implementations
• Special-purpose implementations
• Concurrent implementations
• Wrapper implementations
• Convenience implementations
• Abstract implementations
11
Implementations
12
General Purpose Implementations
13
Algorithms
14
Core Collection
Interfaces
Core Collection Interfaces Hierarchy
16
Core Collection Interfaces
17
“Collection” Interface
“Collection” Interface
• The root of the collection hierarchy
• Is the least common denominator that all collection
implement
> Every collection object is a type of Collection interface
• Is used to pass collection objects around and to
manipulate them when maximum generality is
desired
> Use Collection interface as a type
• JDK doesn't provide any direct implementations of
this interface but provides implementations of more
specific subinterfaces, such as Set and List
19
“Collection” Interface (Java SE 5)
public interface Collection<E> extends Iterable<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array operations
Object[] toArray();
<T> T[] toArray(T[] a);
} 20
Example: Usage “Collection”
Interface as a Type
// Create a ArrayList collection object instance and assign it
// to Collection type.
Collection c1 = new ArrayList();
boolean b1 = c1.isEmpty();
boolean b2 = c1.add(new Integer(1));
21
“Collection” Interface:
add() and remove()
Operations
add() and remove() methods of
Collection Interface
• The add() method is defined generally enough so
that it makes sense for collections that allow
duplicates as well as those that don't
• It guarantees that the Collection will contain the
specified element after the call completes, and
returns true if the Collection changes as a result of
the call.
> add() method of Set interface follows “no duplicate” rule
23
“Collection” Interface:
Traversing
Two Schemes of Traversing
Collections
• for-each
> The for-each construct allows you to concisely traverse a
collection or array using a for loop
for (Object o: collection)
System.out.println(o);
• Iterator
> An Iterator is an object that enables you to traverse through a
collection and to remove elements from the collection
selectively, if desired
25
Iterator Interface
26
Use Iterator over for-each when you
need to
• Remove the current element
> The for-each construct hides the iterator, so you cannot call
remove
> Therefore, the for-each construct is not usable for filtering.
static void filter(Collection<?> c) {
for (Iterator<?> it = c.iterator(); it.hasNext(); )
if (!cond(it.next()))
it.remove();
}
• Iterate over multiple collections in parallel
27
“Collection” Interface:
Bulk Operations
Bulk Operations
• containsAll() — returns true if the target Collection contains
all of the elements in the specified Collection.
• addAll() — adds all of the elements in the specified
Collection to the target Collection.
• removeAll() — removes from the target Collection all of its
elements that are also contained in the specified Collection.
• retainAll() — removes from the target Collection all its
elements that are not also contained in the specified
Collection. That is, it retains only those elements in the
target Collection that are also contained in the specified
Collection.
• clear() — removes all elements from the Collection.
29
Example: removeAll()
30
“Collection” Interface:
Array Operations
Array Operations
32
Example: Array Operations
33
Set Interface &
Implementations
“Set” Interface
35
“Set” Interface (Java SE 5)
public interface Set<E> extends Collection<E> {
// Basic operations
int size();
boolean isEmpty();
boolean contains(Object element);
boolean add(E element); //optional
boolean remove(Object element); //optional
Iterator<E> iterator();
// Bulk operations
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); //optional
boolean removeAll(Collection<?> c); //optional
boolean retainAll(Collection<?> c); //optional
void clear(); //optional
// Array Operations
Object[] toArray();
<T> T[] toArray(T[] a);
} 36
“equals” operation of “Set”
Interface
• Set also adds a stronger contract on the behavior of
the equals and hashCode operations, allowing Set
instances to be compared meaningfully even if their
implementation types differ
> Two Set instances are equal if they contain the same
elements
37
“SortedSet” Interface
38
Implementations of “Set” Interface
• HashSet
• TreeSet
• LinkedHashSet
39
HashSet
• HashSet is much faster than TreeSet (constant-
time versus log-time for most operations) but
offers no ordering guarantees
• Mostly commonly used implementation
40
Caveats of Using HashSet
41
Example: Set Interface & HashSet
public class MyOwnUtilityClass {
// Note that the first parameter type is set to
// Set interface not a particular implementation
// class such as HashSet. This makes the caller of
// this method to pass instances of different
// implementations of Set interface while
// this function picks up polymorphic behavior
// depending on the actual implementation type
// of the object instance passed.
public static void checkDuplicate(Set s, String[] args){
for (int i=0; i<args.length; i++)
if (!s.add(args[i]))
System.out.println("Duplicate detected: "+args[i]);
System.out.println(s.size()+" distinct words detected: "+s);
}
} 42
Example: Set Interface & HashSet
public class Main {
44
TreeSet
• When you need to use the operations in the
SortedSet interface, or if value-ordered iteration is
required
45
Example: Set Interface & TreeSet
public static void main(String[] args) {
Set ts = new TreeSet();
ts.add("one");
ts.add("two");
ts.add("three");
ts.add("four");
ts.add("three");
System.out.println("Members from TreeSet = " + ts);
}
Result:
Members from TreeSet = [four, one, three, two]
46
LinkedHashSet
• Implemented as a hash table with a linked list
running through it
• Provides insertion-ordered iteration (least recently
inserted to most recently) and runs nearly as fast
as HashSet.
• Spares its clients from the unspecified, generally
chaotic ordering provided by HashSet without
incurring the increased cost associated with
TreeSet
47
Example: Set Interface &
LinkedHashSet
public static void main(String[] args) {
Set ts2 = new LinkedHashSet();
ts2.add(2);
ts2.add(1);
ts2.add(3);
ts2.add(3);
System.out.println("Members from LinkedHashSet = " + ts2);
}
Result:
Members from LinkedHashSet = [2, 1, 3]
48
List Interface &
Implementations
“List” Interface
50
Additional Operations Supported by
“List” Interface over “Collection”
• Positional access — manipulates elements based
on their numerical position in the list
• Search — searches for a specified object in the list
and returns its numerical position
• Iteration — extends Iterator semantics to take
advantage of the list's sequential nature
• Range-view — performs arbitrary range operations
on the list.
51
“List” Interface
public interface List<E> extends Collection<E> {
// Positional access
E get(int index);
E set(int index, E element); //optional
boolean add(E element); //optional
void add(int index, E element); //optional
E remove(int index); //optional
boolean addAll(int index,
Collection<? extends E> c); //optional
// Search
int indexOf(Object o);
int lastIndexOf(Object o);
// Iteration
ListIterator<E> listIterator();
ListIterator<E> listIterator(int index);
// Range-view
List<E> subList(int from, int to);
52
Implementations of “List” Interface
• ArrayList
> Offers constant-time positional access
> Fast
> Think of ArrayList as Vector without the synchronization
overhead
> Most commonly used implementation
• LinkedList
> Use it you frequently add elements to the beginning of the List
or iterate over the List to delete elements from its interior
53
Map Interface &
Implementations
“Map” Interface
55
“Map” Interface (Java SE 5)
public interface Map<K,V> {
// Basic operations
V put(K key, V value);
V get(Object key);
V remove(Object key);
boolean containsKey(Object key);
boolean containsValue(Object value);
int size();
boolean isEmpty();
// Bulk operations
void putAll(Map<? extends K, ? extends V> m);
void clear();
// Collection Views
public Set<K> keySet();
public Collection<V> values();
public Set<Map.Entry<K,V>> entrySet();
57
Implementations of “Map” Interface
• HashMap
> Use it you want maximum speed and don't care about
iteration order
> Most commonly used implementation
• TreeMap
> Use it when you need SortedMap operations or key-ordered
Collection-view iteration
• LinkedHashMap
> Use if you want near-HashMap performance and insertion-
order iteration
58
Queue Interface &
Implementations
“Queue” Interface
60
Implementations of Queue Interface
61
Convenience
Implementations
Collections Class
63
Abstract Classes
Abstract Classes
65
Algorithms
Algorithms
• Sorting
• Shuffling
• Routine data manipulation
• Searching
• Composition
• Find extreme values
67
Algorithms
68
Sorting
69
Natural Ordering
• The type of the elements in a List already implements
Comparable interface
• Examples
> If the List consists of String elements, it will be sorted into
alphabetical order
> If it consists of Date elements, it will be sorted into chronological
order
> String and Date both implement the Comparable interface.
Comparable implementations provide a natural ordering for a class,
which allows objects of that class to be sorted automatically
• If you try to sort a list, the elements of which do not
implement Comparable, Collections.sort(list) will throw a
ClassCastException.
70
Sorting by Natural Order of List
71
Sorting by Comparator Interface
72
Sorting by Natural Order of List
74
Routine Data Manipulation
• The Collections class provides five algorithms for doing
routine data manipulation on List objects
> reverse — reverses the order of the elements in a List.
> fill — overwrites every element in a List with the specified value.
This operation is useful for reinitializing a List.
> copy — takes two arguments, a destination List and a source List,
and copies the elements of the source into the destination,
overwriting its contents. The destination List must be at least as
long as the source. If it is longer, the remaining elements in the
destination List are unaffected.
> swap — swaps the elements at the specified positions in a List.
> addAll — adds all the specified elements to a Collection. The
elements to be added may be specified individually or as an array.
75
Searching
77
Collection Framework
Sang Shin
Java Technology Architect
Sun Microsystems, Inc.
sang.shin@sun.com
www.javapassion.com