Collection Framework
Collection Framework
1
OBJECTIVES
¢ To describe the Java Collections Framework hierarchy
¢ To use the common methods defined in the Collection interface for operating
sets and lists
¢ To use the Iterator interface to traverse a collection
¢ To use the for-each loop to simplify traversing a collection
¢ To explore how and when to use HashSet ,LinkedHashSet ,or TreeSet to store
elements
¢ To understand Sorting with example : Bubble Sort
¢ To compare elements using the Comparable interface and the Comparator
interface
¢ To explore how and when to use ArrayList or LinkedList to store elements.
¢ To use the static utility methods in the Collections class for sorting, searching,
shuffling lists, and finding the largest and smallest element in collections.
¢ To compare performance of sets and lists
¢ To distinguish between Vector and ArrayList, and to use the Stack class for
creating stacks
¢ To explore the relationships among Collection, Queue, LinkedList, and
PriorityQueue and to create priority queues using the PriorityQueue class
¢ To tell the differences between Collection and Map, and describe when and
how to use HashMap, LinkedHashMap, and TreeMap to store values
associated with keys
¢ To obtain singleton sets, lists, and maps, and unmodifiable sets, lists, and
maps, using the static methods in the Collections class 2
JAVA COLLECTION FRAMEWORK HIERARCHY
3
JAVA COLLECTION FRAMEWORK HIERARCHY,
CONT.
SortedSet TreeSet
Collection AbstractCollection
Vector Stack
List AbstractList
ArrayList
AbstractSequentialList LinkedList
Deque
SortedMap TreeMap
«interface»
java.util.Iterator<E>
+hasNext(): boolean Returns true if this iterator ha s more elem ents to traverse.
+next(): E Returns the next element from this iterator. 6
+remove(): void Removes the last element obtained using the next method.
THE SET INTERFACE
The Set interface extends the Collection interface. It does
not introduce new methods or constants, but it stipulates
that an instance of Set contains no duplicate elements. The
concrete classes that implement Set must ensure that no
duplicate elements can be added to the set. That is no two
elements e1 and e2 can be in the set such that e1.equals(e2)
is true.
7
THE SET INTERFACE HIERARCHY
«interfac e»
java.util.Collection< E>
«interfac e»
java.util.Set<E>
java.util.AbstractSet<E> «interfac e»
java.util.SortedSet<E>
java.util.HashSet<E> + first(): E
+ H ash Set() + la st(): E
+ H ash Set(c: Co llec tio n< ? ex te nd s E >) + he adS et(to Ele m en t: E ): So rte dS et< E >
+ H ash Set(in itialCa pa city: int) + ta ilS et(from E le m e nt: E ): S orted Se t< E>
+ H ash Set(in itialCa pa city: int, loa d Fac tor: floa t)
«inte rface »
java.util.NavigableSet<E>
java.util.LinkedH ashSet<E>
+p ollF irst(): E
+ Link ed H a sh Set()
+p ollLast(): E
+ Link ed H a sh Set(c: C olle ction <? e xten ds E > )
+low er(e : E): E
+ Link ed H a sh Set(initia lC ap ac ity: in t)
+h ig he r(e : E ):E
+ Link ed H a sh Set(initia lC ap ac ity: in t, lo ad Fa cto r: floa t)
+flo o r(e: E): E
+c eilin g(e: E ): E
java.util.T reeSet<E>
+ Tree Set()
+ Tree Set(c: C olle ction < ? e xten ds E >)
+ Tree Set(co m p arato r: Co m pa rator< ? sup er E> ) 8
+ Tree Set(s: Sorted Set< E> )
THE ABSTRACTSET CLASS
The AbstractSet class is a convenience class that extends
AbstractCollection and implements Set. The AbstractSet
class provides concrete implementations for the equals
method and the hashCode method. The hash code of a set is
the sum of the hash code of all the elements in the set.
Since the size method and iterator method are not
implemented in the AbstractSet class, AbstractSet is an
abstract class.
9
THE HASHSET CLASS
The HashSet class is a concrete class
that implements Set. It can be used to
store duplicate-free elements. For
efficiency, objects added to a hash set
need to implement the hashCode
method in a manner that properly
disperses the hash code.
10
EXAMPLE: USING HASHSET AND ITERATOR
TestHashSet
11
TIP: FOR-EACH LOOP
You can simplify the code using a JDK 1.5 enhanced for
loop without using an iterator, as follows:
12
EXAMPLE: USING LINKEDHASHSET
TestLinkedHashSet
13
TO UNDERSTAND SORTING : EXAMPLE
BUBBLE SORT
2 9 5 4 8 1 2 5 4 8 1 9 2 4 5 1 8 9 2 4 1 5 8 9 1 2 4 5 8 9
2 5 9 4 8 1 2 4 5 8 1 9 2 4 5 1 8 9 2 1 4 5 8 9
2 5 4 9 8 1 2 4 5 8 1 9 2 4 1 5 8 9
2 5 4 8 9 1 2 4 5 1 8 9
2 5 4 8 1 9
(a) 1st pass (b) 2nd pass (c) 3rd pass (d) 4th pass (e) 5th pass
14
THE SORTEDSET INTERFACE AND THE
TREESET CLASS
16
EXAMPLE: USING TREESET TO SORT
ELEMENTS IN A SET
This example creates a hash set filled with
strings, and then creates a tree set for the same
strings. The strings are sorted in the tree set
using the compareTo method in the Comparable
interface. The example also creates a tree set of
geometric objects. The geometric objects are
sorted using the compare method in the
Comparator interface.
TestTreeSet
17
THE COMPARATOR INTERFACE
18
THE COMPARATOR INTERFACE
GeometricObjectComparator
EXAMPLE: THE USING COMPARATOR TO SORT ELEMENTS
IN A SET
21
THE LIST INTERFACE, CONT.
«interface»
java.util.Collection<E>
«interface»
java.util.List<E>
+add(index: int, element:E): boolean Adds a new element at the specified index.
+addAll(index: int, c: Collection<? extends E>) Adds all the elements in c to this list at the specified
: boolean index.
+get(index: int): E Returns the element in this list at the specified index.
+indexOf(element: Object): int Returns the index of the first matching element.
+lastIndexOf(element: Object): int Returns the index of the last matching element.
+listIterator(): ListIterator<E> Returns the list iterator for the elements in this list.
+listIterator(startIndex: int): ListIterator<E> Returns the iterator for the elements from startIndex.
+remove(index: int): E Removes the element at the specified index.
+set(index: int, element: E): E Sets the element at the specified index.
+subList(fromIndex: int, toIndex: int): List<E> Returns a sublist from fromIndex to toIndex.
22
THE LIST ITERATOR
«interface»
java.util.Iterator<E>
«interface»
java.util.ListIterator<E>
23
ARRAYLIST AND LINKEDLIST
The ArrayList class and the LinkedList class are
concrete implementations of the List interface. Which
of the two classes you use depends on your specific
needs. If you need to support random access through
an index without inserting or removing elements from
any place other than the end, ArrayList offers the
most efficient collection. If, however, your application
requires the insertion or deletion of elements from
any place in the list, you should choose LinkedList. A
list can grow or shrink dynamically. An array is fixed
once it is created. If your application does not require
insertion or deletion of elements, the most efficient
data structure is the array.
24
JAVA.UTIL.ARRAYLIST
«interface»
java.util.Collection<E>
«interface»
java.util.List<E>
java.util.ArrayList<E>
«interface»
java.util.List<E>
java.util.LinkedList<E>
TestList
27
THE COLLECTIONS CLASS
The Collections class contains various static methods for
operating on collections and maps, for creating
synchronized collection classes, and for creating read-
only collection classes.
28
PERFORMANCE OF SETS AND LISTS
SetListPerformanceTest
29
THE COLLECTIONS CLASS UML
DIAGRAM
java.util.Collections
+sort(list: List): void Sorts the specified list.
+sort(list: List, c: Comparator): void Sorts the specified list with the comparator.
+binarySearch(list: List, key: Object): int Searches the key in the sorted list using binary search.
+binarySearch(list: List, key: Object, c: Searches the key in the sorted list using binary search
Comparator): int with the comparator.
List +reverse(list: List): void Reverses the specified list.
+reverseOrder(): Comparator Returns a comparator with the reverse ordering.
+shuffle(list: List): void Shuffles the specified list randomly.
+shuffle(list: List): void Shuffles the specified list with a random object.
+copy(des: List, src: List): void Copies from the source list to the destination list.
+nCopies(n: int, o: Object): List Returns a list consisting of n copies of the object.
+fill(list: List, o: Object): void Fills the list with the object.
+max(c: Collection): Object Returns the max object in the collection.
+max(c: Collection, c: Comparator): Object Returns the max object using the comparator.
+min(c: Collection): Object Returns the min object in the collection.
Collection +min(c: Collection, c: Comparator): Object Returns the min object using the comparator.
+disjoint(c1: Collection, c2: Collection): Returns true if c1 and c2 have no elements in common.
boolean
+frequency(c: Collection, o: Object): int Returns the number of occurrences of the specified 30
element in the collection.
EXAMPLE: USING THE COLLECTIONS CLASS
TestCollections
31
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo hi
32
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo mid hi
33
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo hi
34
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo mid hi
35
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo hi
36
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo mid hi
37
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo
hi
38
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo
hi
mid 39
BINARY SEARCH
¢ Binary search. Given value and sorted array a[],
find index i
such that a[i] = value, or report that no such index
exists.
¢ Invariant. Algorithm maintains a[lo] £ value £
a[hi].Ex. Binary search for 33.
6 13 14 25 33 43 51 53 64 72 84 93 95 96 97
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
lo
hi
mid 40
BINARY SEARCH : TIME COMPLEXITY
¢ Binary search (half the elements) is performed
until you found the search value or when low >
high condition is reached.
¢ Basically, divide the array into half in every
iteration until the result becomes 1. It is
represented as 1 = N / 2x
multiply by 2x:
2x = N
now take log2 on both sides:
log2(2x) = log2 N
x * log2(2) = log2 N
x*1 = log2 N 41
¢ It means , you can divide log N ("do the binary
search step") until you found your element.
THE VECTOR AND STACK CLASSES
42
THE VECTOR CLASS
43
THE VECTOR CLASS, CONT.
«interface»
java.util.List<E>
java.util.Vector<E>
+Vector() Creates a default empty vector with initial capacity 10.
+Vector(c: Collection<? extends E>) Creates a vector from an existing collection.
+Vector(initialCapacity: int) Creates a vector with the specified initial capacity.
+Vector(initCapacity:int, capacityIncr: int) Creates a vector with the specified initial capacity and increment.
+addElement(o: E): void Appends the element to the end of this vector.
+capacity(): int Returns the current capacity of this vector.
+copyInto(anArray: Object[]): void Copies the elements in this vector to the array.
+elementAt(index: int): E Returns the object at the specified index.
+elements(): Enumeration<E> Returns an enumeration of this vector.
+ensureCapacity(): void Increases the capacity of this vector.
+firstElement(): E Returns the first element in this vector.
+insertElementAt(o: E, index: int): void Inserts o to this vector at the specified index.
+lastElement(): E Returns the last element in this vector.
+removeAllElements(): void Removes all the elements in this vector.
+removeElement(o: Object): boolean Removes the first matching element in this vector.
+removeElementAt(index: int): void Removes the element at the specified index.
+setElementAt(o: E, index: int): void Sets a new element at the specified index.
+setSize(newSize: int): void Sets a new size in this vector.
44
+trimToSize(): void Trims the capacity of this vector to its size.
THE STACK CLASS
The Stack class represents a last-in-
first-out stack of objects. The elements
are accessed only from the top of the
java.util.Vector<E> stack. You can retrieve, insert, or
remove an element from the top of the
java.util.Stack<E> stack.
46
THE QUEUE INTERFACE
«interface»
java.util.Collection<E>
«interface»
java.util.Queue<E>
«interface»
java.util.Queue<E>
java.util.PriorityQueue<E>
+PriorityQueue() Creates a default priority queue with initial capacity 11.
+PriorityQueue(initialCapacity: int) Creates a default priority queue with the specified initial
capacity.
+PriorityQueue(c: Collection<? extends Creates a priority queue with the specified collection.
E>)
+PriorityQueue(initialCapacity: int, Creates a priority queue with the specified initial
comparator: Comparator<? super E>) capacity and the comparator.
PriorityQueueDemo
48
THE MAP INTERFACE
The Map interface maps keys to the elements. The keys
are like indexes. In List, the indexes are integer. In Map,
the keys can be any objects.
Entry
…
.
.
49
THE MAP INTERFACE UML DIAGRAM
java.util.Map<K, V>
+clear(): void Removes all mappings from this map.
+containsKey(key: Object): boolean Returns true if this map contains a mapping for the
specified key.
+containsValue(value: Object): boolean Returns true if this map maps one or more keys to the
specified value.
+entrySet(): Set Returns a set consisting of the entries in this map.
+get(key: Object): V Returns the value for the specified key in this map.
+isEmpty(): boolean Returns true if this map contains no mappings.
+keySet(): Set<K> Returns a set consisting of the keys in this map.
+put(key: K, value: V): V Puts a mapping in this map.
+putAll(m: Map): void Adds all the mappings from m to this map.
+remove(key: Object): V Removes the mapping for the specified key.
+size(): int Returns the number of mappings in this map.
+values(): Collection<V> Returns a collection consisting of the values in this map.
50
CONCRETE MAP CLASSES
«interface»
java.util.Map<K, V>
java.util.LinkedHashMap<K, V>
+LinkedHashMap() java.util.TreeMap<K, V>
+LinkedHashMap(m: Map) +TreeMap()
+LinkedHashMap(initialCapacity: int, +TreeMap(m: Map) 51
loadFactor: float, accessOrder: boolean) +TreeMap(c: Comparator<? super K>)
HASHMAP AND TREEMAP
The HashMap and TreeMap classes are
two concrete implementations of the
Map interface. The HashMap class is
efficient for locating a value, inserting
a mapping, and deleting a mapping.
The TreeMap class, implementing
SortedMap, is efficient for traversing
the keys in a sorted order.
52
LINKEDHASHMAP
LinkedHashMap was introduced in JDK 1.4. It
extends HashMap with a linked list
implementation that supports an ordering of the
entries in the map. The entries in a HashMap are
not ordered, but the entries in a LinkedHashMap
can be retrieved in the order in which they were
inserted into the map (known as the insertion
order), or the order in which they were last
accessed, from least recently accessed to most
recently (access order). The no-arg constructor
constructs a LinkedHashMap with the insertion
order. To construct a LinkedHashMap with the
access order, use the
LinkedHashMap(initialCapacity, loadFactor, true).
53
EXAMPLE: USING HASHMAP AND TREEMAP
CountOccurrenceOfWords 55
THE ARRAYS CLASS
56
THE ARRAYS CLASS UML DIAGRAM
Arrays
+asList(a: Object[]): List Returns a list from an array of objects
Overloaded binarySearch method for byte, char, Overloaded binary search method to search a key
short, int, long, float, double, and Object. in the array of byte, char, short, int, long, float,
+binarySearch(a: xType[], key: xType): int double, and Object
Overloaded equals method for boolean, byte, Overloaded equals method that returns true if a is
char, short, int, long, float, double, and Object. equal to a2 for a and a2 of the boolean, byte, char,
+equals(a: xType[], a2: xType[]): boolean short, int, long, float, and Object type
Overloaded fill method for boolean char, byte, Overloaded fill method to fill in the specified
short, int, long, float, double, and Object. value into the array of the boolean, byte, char,
+fill(a: xType[], val: xType): void short, int, long, float, and Object type
+fill(a: xType[], fromIndex: int, toIndex: xType,
val: xType): void
Overloaded sort method for char, byte, short, int, Overloaded sort method to sort the specified array
long, float, double, and Object. of the char, byte, short, int, long, float, double,
+sort(a: xType[]): void and Object type
+sort(a: xType[], fromIndex: int, toIndex: int):
void 57
EXAMPLE: USING THE ARRAYS CLASS
TestArrays
58