JAVA COLLECTIONS 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
A collection is a container object that
represents a group of objects, often
referred to as elements. The Java
Collections Framework supports three
types of collections, named sets, lists, and
maps.
3
JAVA COLLECTION FRAMEWORK HIERARCHY,
CONT.
Set and List are subinterfaces of Collection.
SortedSet TreeSet
Set AbstractSet HashSet LinkedHashSet
Collection AbstractCollection
Vector Stack
List AbstractList
ArrayList
AbstractSequentialList LinkedList
Deque
Queue AbstractQueue PriorityQueue
Interfaces Abstract Classes Concrete Classes
JAVA COLLECTION FRAMEWORK HIERARCHY,
CONT.
An instance of Map represents a group of objects,
each of which is associated with a key. You can get
the object from a map using a key, and you have to
use a key to put the object into the map.
SortedMap TreeMap
Map AbstractMap HashMap LinkedHashMap
Interfaces Abstract Classes Concrete Classes
5
THE COLLECTION INTERFACE
The Collection interface is the root interface
for manipulating a collection of objects.
«interface»
java.util.Collection<E>
+add(o: E): boolean Adds a new element o to this collection.
+addAll(c: Collection<? extends E>): boolean Adds all the elements in the collection c to this collection.
+clear(): void Removes all the elements from this collection.
+contains(o: Object): boolean Returns true if this collection contains the element o.
+containsAll(c: Collection<?>):boole an Returns true if this collection contains all the elements in c.
+equals(o: Object): boolean Returns true if this collection is equal to another collection o.
+hashCode(): int Returns the hash c ode for this collection.
+isEmpty(): boolean Returns true if this collection contains no elem ents.
+iterator(): Iterator Returns an iterator for the elements in this collection.
+remove (o: Object): boolean Removes the elem ent o from this collection.
+remove All(c: Collection<?>): boolean Removes all the elements in c from this collection.
+retainAll(c: Collection<?>): boolean Retains the elements that are both in c and in this collection.
+size (): int Returns the number of elem ents in this collection.
+toArray(): Object[] Returns an array of Object for the elements in this collection.
«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
This example creates a hash set filled
with strings, and uses an iterator to
traverse the elements in the list.
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:
for (Object element: set)
System.out.print(element.toString() + " ");
12
EXAMPLE: USING LINKEDHASHSET
This example creates a hash set filled
with strings, and uses an iterator to
traverse the elements in the list.
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
Bubble sort time: O(n2)
n2 n
(n - 1) + (n - 2) + ... + 2 + 1 = -
2 2
14
THE SORTEDSET INTERFACE AND THE
TREESET CLASS
SortedSet is a subinterface of Set,
which guarantees that the elements in
the set are sorted. TreeSet is a
concrete class that implements the
SortedSet interface. You can use an
iterator to traverse the elements in the
sorted order. The elements can be
sorted in two ways.
15
THE SORTEDSET INTERFACE AND THE
TREESET CLASS, CONT.
One way is to use the Comparable interface.
The other way is to specify a comparator for the elements
in the set if the class for the elements does not implement
the Comparable interface, or you don’t want to use the
compareTo method in the class that implements the
Comparable interface. This approach is referred to as
order by comparator.
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
Sometimes you want to insert elements of
different types into a tree set. The elements may
not be instances of Comparable or are not
comparable. You can define a comparator to
compare these elements. To do so, create a class
that implements the java.util.Comparator
interface. The Comparator interface has two
methods, compare and equals.
18
THE COMPARATOR INTERFACE
public int compare(Object element1, Object
element2)
Returns a negative value if element1 is less than
element2, a positive value if element1 is greater
than element2, and zero if they are equal.
public boolean equals(Object element)
Returns true if the specified object is also a
comparator and imposes the same ordering as
this comparator. 19
GeometricObjectComparator
EXAMPLE: THE USING COMPARATOR TO SORT ELEMENTS
IN A SET
Write a program that demonstrates
how to sort elements in a tree set
using the Comparator interface. The
example creates a tree set of geometric
objects. The geometric objects are
sorted using the compare method in
the Comparator interface.
TestTreeSetWithComparator
20
THE LIST INTERFACE
A set stores non-duplicate elements. To
allow duplicate elements to be stored in a
collection, you need to use a list. A list
can not only store duplicate elements,
but can also allow the user to specify
where the element is stored. The user
can access the element by index.
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>
+add(o: E): void Adds the specified object to the list.
+hasPrevious(): boolean Returns true if this list iterator has more elements
when traversing backward.
+nextIndex(): int Returns the index of the next element.
+previous(): E Returns the previous element in this list iterator.
+previousIndex(): int Returns the index of the previous element.
+set(o: E): void Replaces the last element returned by the previous or
next method with the specified element.
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>
+ArrayList() Creates an empty list with the default initial capacity.
+ArrayList(c: Collection<? extends E>) Creates an array list from an existing collection.
+ArrayList(initialCapacity: int) Creates an empty list with the specified initial capacity.
+trimToSize(): void Trims the capacity of this ArrayList instance to be the
list's current size.
25
JAVA.UTIL.LINKEDLIST
«interface»
java.util.Collection<E>
«interface»
java.util.List<E>
java.util.LinkedList<E>
+LinkedList() Creates a default empty linked list.
+LinkedList(c: Collection<? extends E>) Creates a linked list from an existing collection.
+addFirst(o: E): void Adds the object to the head of this list.
+addLast(o: E): void Adds the object to the tail of this list.
+getFirst(): E Returns the first element from this list.
+getLast(): E Returns the last element from this list.
+removeFirst(): E Returns and removes the first element from this list.
+removeLast(): E Returns and removes the last element from this list. 26
EXAMPLE: USING ARRAYLIST AND
LINKEDLIST
This example creates an array list filled
with numbers, and inserts new elements
into the specified location in the list. The
example also creates a linked list from
the array list, inserts and removes the
elements from the list. Finally, the
example traverses the list forward and
backward.
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
This example demonstrates using the methods in the
Collections class. The example creates a list, sorts it,
and searches for an element. The example wraps the
list into a synchronized and read-only list.
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
The Java Collections Framework was introduced with
Java 2. Several data structures were supported prior to
Java 2. Among them are the Vector class and the Stack
class. These classes were redesigned to fit into the Java
Collections Framework, but their old-style methods are
retained for compatibility. This section introduces the
Vector class and the Stack class.
42
THE VECTOR CLASS
In Java 2, Vector is the same as ArrayList, except that
Vector contains the synchronized methods for accessing
and modifying the vector. None of the new collection
data structures introduced so far are synchronized. If
synchronization is required, you can use the
synchronized versions of the collection classes.
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.
+Stack() Creates an empty stack.
+empty(): boolean Returns true if this stack is empty.
+peek(): E Returns the top element in this stack.
+pop(): E Returns and removes the top element in this stack.
+push(o: E) : E Adds a new element to the top of this stack.
+search(o: Object) : int Returns the position of the specified element in this stack.
45
QUEUES AND PRIORITY QUEUES
A queue is a first-in/first-out data structure. Elements are
appended to the end of the queue and are removed from the
beginning of the queue. In a priority queue, elements are
assigned priorities. When accessing elements, the element
with the highest priority is removed first.
46
THE QUEUE INTERFACE
«interface»
java.util.Collection<E>
«interface»
java.util.Queue<E>
+offer(element: E): boolean Inserts an element to the queue.
+poll(): E Retrieves and removes the head of this queue, or null
if this queue is empty.
+remove(): E Retrieves and removes the head of this queue and
throws an exception if this queue is empty.
+peek(): E Retrieves, but does not remove, the head of this queue,
returning null if this queue is empty.
+element(): E Retrieves, but does not remove, the head of this queue,
throwing an exception if this queue is empty.
47
THE PRIORITYQUEUE CLASS
«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.
Search keys Corresponding values
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.AbstractMap<K, V> «interface»
java.util.SortedMap<K, V>
+firstKey(): K
+lastKey(): K
java.util.HashMap<K, V>
+comparator(): Comparator<? super K>)
+HashMap() +headMap(toKey: K): SortedMap
+HashMap(m: Map)
+tailMap(fromKey: K): SortedMap
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
This example creates a hash map that
maps borrowers to mortgages. The
program first creates a hash map with
the borrower’s name as its key and
mortgage as its value. The program
then creates a tree map from the hash
map, and displays the mappings in
ascending order of the keys.
TestMap
54
EXAMPLE: COUNTING THE OCCURRENCES OF
WORDS IN A TEXT
This program counts the occurrences of words in a text and
displays the words and their occurrences in ascending order of
the words. The program uses a hash map to store a pair
consisting of a word and its count. For each word, check
whether it is already a key in the map. If not, add the key and
value 1 to the map. Otherwise, increase the value for the word
(key) by 1 in the map. To sort the map, convert it to a tree
map.
CountOccurrenceOfWords 55
THE ARRAYS CLASS
The Arrays class contains various static methods for
sorting and searching arrays, for comparing arrays, and
for filling array elements. It also contains a method for
converting an array to a list.
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
This example demonstrates using the methods in the
Arrays class. The example creates an array of int
values, fills part of the array with 50, sorts it,
searches for an element, and compares the array
with another array.
TestArrays
58