BCS613D –Advanced JAVA
Module 1
The Collections and Frame work
Collections overview:
The Collection framework consists of the following core interfaces:
a) Collection Interface (Root)
The Collection interface is the root of the collection framework.
Subinterfaces: List, Set, Queue, Deque.
b) List Interface (Ordered, Duplicates Allowed)
Implementation Classes:
ArrayList (Dynamic array, fast read, slow inserts/removals)
LinkedList (Doubly linked list, fast inserts/removals, slow read)
Vector (Similar to ArrayList, synchronized)
Stack (LIFO - Last In, First Out)
c) Set Interface (Unique Elements, Unordered)
Implementation Classes:
HashSet (No duplicates, unordered, fast access)
Sandhya P N , Dept of CSE , CIT , Gubbi Page 1
BCS613D –Advanced JAVA
LinkedHashSet (Maintains insertion order)
TreeSet (Sorted, implements NavigableSet)
d) Queue Interface (FIFO - First In, First Out)
Implementation Classes:
PriorityQueue (Ordered based on priority, uses a heap)
LinkedList (Can also be used as a queue)
e) Deque Interface (Double-Ended Queue)
Implementation Classes:
ArrayDeque (Faster than Stack for push/pop operations)
2. Map Interface (Key-Value Pairs, Not Part of Collection)
Although Map is not a part of the Collection interface, it is an important part of the
framework.
Implementation Classes:
HashMap (Unordered key-value pairs, allows one null key)
LinkedHashMap (Maintains insertion order)
TreeMap (Sorted based on keys, implements NavigableMap)
Hashtable (Thread-safe, does not allow null keys)
The Collection Interfaces:
The Collection interface is the foundation upon which the Collections Framework is built
because it must be implemented by any class that defines a collection.
Collection is a generic interface that has this declaration:
interface Collection<E>
Sandhya P N , Dept of CSE , CIT , Gubbi Page 2
BCS613D –Advanced JAVA
Here, E specifies the type of objects that the collection will hold. Collection extends the
Iterable interface. This means that all collections can be cycled through by use of the for each
style for loop.
The List Interface
The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements. Elements can be inserted or accessed by their position in the list, using
a zero-based index. A list may contain duplicate elements.
List is a generic interface that has this declaration:
interface List<E>
Here, E specifies the type of objects that the list will hold.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 3
BCS613D –Advanced JAVA
The Set Interface
The Set interface defines a set. It extends Collection and specifies the behavior of a collection
that does not allow duplicate elements. Therefore, the add( ) method returns false if an
attempt is made to add duplicate elements to a set. With two exceptions, it does not specify
any additional methods of its own. Set is a generic interface that has this declaration:
interface Set<E>
Here, E specifies the type of objects that the set will hold.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 4
BCS613D –Advanced JAVA
The SortedSet Interface
The SortedSet interface extends Set and declares the behavior of a set sorted in ascending
order. SortedSet is a generic interface that has this declaration:
interface SortedSet<E>
Here, E specifies the type of objects that the set will hold.
SortedSet defines several methods that make set processing more convenient. To obtain the
first object in the set, call first( ). To get the last element, use last( ). You can obtain a subset
of a sorted set by calling subSet( ), specifying the first and last object in the set. If you need
the subset that starts with the first element in the set, use headSet( ). If you want the subset
that ends the set, use tailSet( ).
The NavigableSet Interface
The NavigableSet interface extends SortedSet and declares the behavior of a collection that
supports the retrieval of elements based on the closest match to a given value or values.
NavigableSet is a generic interface that has this declaration:
interface NavigableSet<E>
Here, E specifies the type of objects that the set will hold.
In addition to the methods that it inherits from SortedSet, NavigableSet adds those
summarized in Table
Sandhya P N , Dept of CSE , CIT , Gubbi Page 5
BCS613D –Advanced JAVA
The Queue Interface
The Queue interface extends Collection and declares the behavior of a queue, which is often a
first-in, first-out list. However, there are types of queues in which the ordering is based upon
other criteria.
Queue is a generic interface that has this declaration:
Sandhya P N , Dept of CSE , CIT , Gubbi Page 6
BCS613D –Advanced JAVA
interface Queue<E>
Here, E specifies the type of objects that the queue will hold. The methods declared by
Queue are shown in Table
The Deque Interface
The Deque interface extends Queue and declares the behavior of a double-ended queue.
Double-ended queues can function as standard, first-in, first-out queues or as last-in, firstout
stacks.
Deque is a generic interface that has this declaration:
interface Deque<E>
Here, E specifies the type of objects that the deque will hold. In addition to the methods that
it inherits from Queue, Deque adds those methods summarized in Table
Sandhya P N , Dept of CSE , CIT , Gubbi Page 7
BCS613D –Advanced JAVA
The Collection Classes
A Collection class is a type of class used to store, manage, and manipulate groups of objects
in a structured way. It is commonly found in programming languages that support object-
oriented programming (OOP). Collection classes typically provide methods for adding,
removing, searching, sorting, and iterating over elements.
Collection Class in Java
In Java, the Collection Framework provides built-in collection classes such as:
List Interface (Ordered, allows duplicates)
ArrayList
LinkedList
Vector
Stack
Sandhya P N , Dept of CSE , CIT , Gubbi Page 8
BCS613D –Advanced JAVA
Set Interface (No duplicates, unordered or sorted)
HashSet
LinkedHashSet
TreeSet
Queue Interface (FIFO order)
PriorityQueue
Deque (e.g., ArrayDeque)
Map Interface (Key-Value pairs, not part of Collection but important)
HashMap
LinkedHashMap
TreeMap
Hashtable
The ArrayList Class
The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:
class ArrayList<E>
Here, E specifies the type of objects that the list will hold.
ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a
fixed length. After arrays are created, they cannot grow or shrink, which means that you must
know in advance how many elements an array will hold. But, sometimes, you may not know
until run time precisely how large an array you need. To handle this situation, the Collections
Sandhya P N , Dept of CSE , CIT , Gubbi Page 9
BCS613D –Advanced JAVA
Framework defines ArrayList. In essence, an ArrayList is a variable-length array of object
references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are
created with an initial size. When this size is exceeded, the collection is automatically
enlarged. When objects are removed, the array can be shrunk.
NOTE: In addition to the collection classes, several legacy classes, such as Vector, Stack,
and Hashtable, have been reengineered to support collections. Dynamic arrays are also
supported by the legacy class Vector
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list. The second constructor builds an array list
that is initialized with the elements of the collection c. The third constructor builds an array
list that has the specified initial capacity. The capacity is the size of the underlying array that
is used to store the elements. The capacity grows automatically as elements are added to an
array list.
The following program shows a simple use of ArrayList. An array list is created for
objects of type String, and then several strings are added to it. (Recall that a quoted string
is translated into a String object.) The list is then displayed. Some of the elements are
removed and the list is displayed again.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 10
BCS613D –Advanced JAVA
Notice that al starts out empty and grows as elements are added to it. When elements are
removed, its size is reduced.
Obtaining an Array from an ArrayList
When working with ArrayList, you will sometimes want to obtain an actual array that
contains the contents of the list. You can do this by calling toArray( ), which is defined by
Collection.
Several reasons exist why you might want to convert a collection into an array, such as:
• To obtain faster processing times for certain operations
• To pass an array to a method that is not overloaded to accept a collection
• To integrate collection-based code with legacy code that does not understand collections
Sandhya P N , Dept of CSE , CIT , Gubbi Page 11
BCS613D –Advanced JAVA
The LinkedList Class
The LinkedList class extends AbstractSequentialList and implements the List, Deque, and
Queue interfaces. It provides a linked-list data structure.
LinkedList is a generic class that has this declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold.
LinkedList has the two constructors shown here:
LinkedList( )
LinkedList(Collection<? extends E> c)
The first constructor builds an empty linked list. The second constructor builds a linked list
that is initialized with the elements of the collection c. Because LinkedList implements the
Deque interface, you have access to the methods defined by Deque. For example, to add
elements to the start of a list, you can use addFirst( ) or offerFirst( ). To add elements to the
end of the list, use addLast( ) or offerLast( ). To obtain the first element, you can use getFirst(
) or peekFirst( ). To obtain the last element, use getLast( ) or peekLast( ). To remove the first
element, use removeFirst( ) or pollFirst( ). To remove the last element, use removeLast( ) or
pollLast( ).
Sandhya P N , Dept of CSE , CIT , Gubbi Page 12
BCS613D –Advanced JAVA
Key Features of LinkedList
Doubly linked list: Each node contains a reference to both the next and previous node.
Fast insertions and deletions: Adding/removing elements at the beginning or middle is
efficient.
Ordered collection: Maintains insertion order.
Allows duplicates: Can store multiple occurrences of the same element.
Can store null values.
Implements List, Deque, and Queue: Supports stack, queue, and deque operations.
The following program illustrates LinkedList:
Output:
Sandhya P N , Dept of CSE , CIT , Gubbi Page 13
BCS613D –Advanced JAVA
The HashSet Class
The HashSet class in Java is part of the java.util package and implements the Set interface
using a hash table. It is used to store unique elements and does not maintain insertion order.
Key Features of HashSet
No duplicates: Stores only unique elements.
Unordered collection: Does not maintain insertion order.
Allows null values.
Fast performance: Provides O(1) time complexity for add, remove, and contains
operations.
Backed by a HashMap: Internally uses a HashMap for storage.
HashSet extends AbstractSet and implements the Set interface. It creates a collection that
uses a hash table for storage. HashSet is a generic class that has this declaration:
class HashSet<E>
Here, E specifies the type of objects that the set will hold.
As most readers likely know, a hash table stores information by using a mechanism called
hashing. In hashing, the informational content of a key is used to determine a unique value,
called its hash code. The hash code is then used as the index at which the data associated
with the key is stored. The transformation of the key into its hash code is performed
automatically—you never see the hash code itself. Also, your code can’t directly index the
hash table.
The advantage of hashing is that it allows the execution time of add( ), contains( ),
remove( ), and size( ) to remain constant even for large sets.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 14
BCS613D –Advanced JAVA
The LinkedHashSet Class
The LinkedHashSet class in Java is part of the java.util package and implements the Set
interface using a combination of a HashSet and a linked list. It maintains the insertion order
while ensuring that elements are unique.
The LinkedHashSet class extends HashSet and adds no members of its own.
It is a generic class that has this declaration:
class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold. Its constructors parallel those in
HashSet.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 15
BCS613D –Advanced JAVA
The TreeSet Class
The TreeSet class in Java is part of the java.util package and implements the SortedSet
interface . It maintains elements in sorted order and ensures unique values.
Key Features of TreeSet
Maintains sorted order: Elements are stored in ascending order (natural ordering or
custom comparator).
No duplicates: Ensures only unique elements are stored.
Implements SortedSet and NavigableSet.
Does not allow null values (unlike HashSet or LinkedHashSet).
Provides methods for range queries (first, last, higher, lower, subset, etc.).
Slower than HashSet but useful for sorted data storage.
The PriorityQueue Class
The PriorityQueue class in Java is part of the java.util package and implements a queue
where elements are processed based on their priority rather than the order they were added. It
uses a min-heap (by default) to always keep the smallest element at the front.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 16
BCS613D –Advanced JAVA
Key Features of PriorityQueue
Elements are ordered by priority (natural ordering or custom comparator).
Does not allow null values.
Duplicates are allowed.
Uses a min-heap by default (smallest element at the head).
Non-thread-safe (Use PriorityBlockingQueue for thread safety).
Faster than sorting a list for priority-based processing.
The ArrayDeque Class
The ArrayDeque class in Java is part of the java.util package and implements a resizable,
double-ended queue (Deque). It allows adding and removing elements from both ends
efficiently, making it a versatile alternative to Stack and Queue.
The EnumSet Class
The EnumSet class in Java is a specialized Set implementation designed exclusively for use
with enum types. It is part of the java.util package and provides a high-performance,
memory-efficient way to store enum values.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 17
BCS613D –Advanced JAVA
Accessing a Collection via an Iterator
What is an Iterator?
Accessing a collection via an iterator allows you to traverse its elements
sequentially without exposing the underlying structure. This is especially useful when
dealing with large datasets, as it avoids loading everything into memory at once.
Why Use an Iterator?
Works for any Collection type (ArrayList, HashSet, LinkedList, etc.)
Supports dynamic modifications (removing elements safely during iteration)
Avoids IndexOutOfBoundsException when accessing elements dynamically
Provides uniform traversal for different collection types
Using an Iterator in Java
In general, to use an iterator to cycle through the contents of a collection,
follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s iterator( )
method.
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
The Iterator interface provides the following methods:
hasNext() → Returns true if there are more elements in the collection.
next() → Returns the next element in the collection.
remove() → Removes the last element returned by next() (optional operation).
Example: Using an Iterator with an ArrayList
Sandhya P N , Dept of CSE , CIT , Gubbi Page 18
BCS613D –Advanced JAVA
List Iterators in Java
In Java, ListIterator is an interface that allows bidirectional traversal of a list (both forward
and backward). It is an enhancement over the standard Iterator, which only supports forward
iteration.
Methods Provided by ListIterator
The ListIterator interface provides the following methods:
Sandhya P N , Dept of CSE , CIT , Gubbi Page 19
BCS613D –Advanced JAVA
Example Usage of ListIterator Iterating Forward and Backward
Sandhya P N , Dept of CSE , CIT , Gubbi Page 20
BCS613D –Advanced JAVA
Modifying List with ListIterator
Key Differences Between Iterator and ListIterator
Sandhya P N , Dept of CSE , CIT , Gubbi Page 21
BCS613D –Advanced JAVA
When to Use ListIterator?
When both forward and backward traversal is needed.
When you need to modify a list while iterating (e.g., add, remove, replace elements).
When working specifically with List implementations (ArrayList, LinkedList, etc.).
The For-Each Alternative to Iterators
The for-each loop (enhanced for loop) is a simpler alternative to using an explicit Iterator or
ListIterator when iterating over collections or arrays. It provides a more concise and readable
way to iterate over elements without manually handling Iterator methods like next(),
hasNext(), or remove().
Sandhya P N , Dept of CSE , CIT , Gubbi Page 22
BCS613D –Advanced JAVA
Spliterators
A Spliterator (short for "Splittable Iterator") is an interface introduced in Java 8 to traverse
and partition elements of a source (such as collections, arrays, or streams) in parallel and
sequential processing.
Key Features of Spliterator
Supports both sequential and parallel traversal.
Can split itself into smaller parts for parallel processing.
Supports functional programming (works with Streams and Lambda expressions).
Offers better performance in parallel processing.
Using Spliterator for basic iteration tasks is quite easy: simply call tryAdvance( ) until
it returns false. If you will be applying the same action to each element in the sequence,
forEachRemaining( ) offers a streamlined alternative.
The Methods Declared by Spliterator
Sandhya P N , Dept of CSE , CIT , Gubbi Page 23
BCS613D –Advanced JAVA
Example: Using Spliterator with an ArrayList
spliterator.tryAdvance()
The tryAdvance() method of Spliterator is used to process one element at a time. It applies a
given action (a Consumer) to the next available element and moves the cursor forward.
Syntax:
boolean tryAdvance(Consumer<? super T> action)
Returns: true if an element was processed, false if no more elements are left.
Parameters: A Consumer function that processes each element.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 24
BCS613D –Advanced JAVA
spliterator.forEachRemaining()
The forEachRemaining() method of Spliterator is used to process all remaining elements in
one go, applying a given action to each element.
Syntax :
void forEachRemaining(Consumer<? super T> action)
Processes all remaining elements in the Spliterator.
Parameters: A Consumer function that operates on each element.
Does not return a value.
The RandomAccess Interface
The RandomAccess interface in Java is a marker interface in the java.util package. It is used
to indicate that a List implementation provides fast (generally constant time) random access
to elements.
Key Points About RandomAccess Interface
Marker Interface
It does not define any methods.
It only serves as a tag for efficient List implementations.
Purpose
It helps algorithms decide whether to use random access or sequential access while iterating
over a list.
Implemented By
Lists that provide fast access (like ArrayList) implement RandomAccess.
Lists that provide sequential access (like LinkedList) do not implement RandomAccess.
If a method processes a list, it can check whether the list implements RandomAccess to
choose the best way to iterate:
For RandomAccess lists: Use indexed for loops.
For non-RandomAccess lists: Use iterators (to avoid performance issues with
LinkedList.get(index))
Sandhya P N , Dept of CSE , CIT , Gubbi Page 25
BCS613D –Advanced JAVA
Storing User-Defined Classes in Collections
Java Collections can store user-defined objects just like built-in types (Integer, String, etc.).
This is useful when working with custom data models in applications. collections are not
limited to the storage of built-in objects. Quite the contrary. The power of collections is that
they can store any type of object, including objects of classes that you create.
For example, consider the following example that uses a LinkedList to store mailing
addresses:
Output :
Sandhya P N , Dept of CSE , CIT , Gubbi Page 26
BCS613D –Advanced JAVA
. Working with Maps
A map is an object that stores associations between keys and values, or key/value pairs.
Given a key, you can find its value. Both keys and values are objects. The keys must be
unique, but the values may be duplicated. Some maps can accept a null key and null values,
others cannot.
There is one key point about maps that is important to mention at the outset: they don’t
implement the Iterable interface. This means that you cannot cycle through a map using a
for-each style for loop. Furthermore, you can’t obtain an iterator to a map. However, as you
will soon see, you can obtain a collection-view of a map, which does allow the use of either
the for loop or an iterator.
The Map Interfaces
Because the map interfaces define the character and nature of maps, this discussion of maps
begins with them. The following interfaces support maps:
The Map interface maps unique keys to values. A key is an object that you use to retrieve a
value at a later date. Given a key and a value, you can store the value in a Map object. After
the value is stored, you can retrieve it by using its key.
Maps revolve around two basic operations: get( ) and put( ). To put a value into a map,
use put( ), specifying the key and the value. To obtain a value, call get( ), passing the key as
an argument. The value is returned.
The Methods Declared by Map :
Sandhya P N , Dept of CSE , CIT , Gubbi Page 27
BCS613D –Advanced JAVA
The SortedMap Interface
The SortedMap interface extends Map. It ensures that the entries are maintained in
ascending order based on the keys. Sorted maps allow very efficient manipulations of
submaps .To obtain a submap, use headMap( ), tailMap( ), or subMap( ). The submap
returned by these methods is backed by the invoking map. Changing one changes the other.
To get the first key in the set, call firstKey( ). To get the last key, use lastKey( ).
The NavigableMap Interface
The NavigableMap interface extends SortedMap and declares the behavior of a map
that supports the retrieval of entries based on the closest match to a given key or keys.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 28
BCS613D –Advanced JAVA
The Map Classes
The HashMap class
The HashMap class extends AbstractMap and implements the Map interface. It uses a
hash table to store the map. This allows the execution time of get( ) and put( ) to remain
constant even for large sets.
The following program illustrates HashMap. It maps names to account balances. Notice
how a set-view is obtained and used.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 29
BCS613D –Advanced JAVA
The TreeMap Class
The TreeMap class extends AbstractMap and implements the NavigableMap interface. It
creates maps stored in a tree structure. A TreeMap provides an efficient means of storing
key/value pairs in sorted order and allows rapid retrieval. You should note that, unlike a hash
map, a tree map guarantees that its elements will be sorted in ascending key order
Sandhya P N , Dept of CSE , CIT , Gubbi Page 30
BCS613D –Advanced JAVA
COMPARATORS
Both TreeSet and TreeMap store elements in sorted order. However, it is the comparator that
defines precisely what “sorted order” means. By default, these classes store their elements
by using what Java refers to as “natural ordering,” which is usually the ordering that you
would expect (A before B, 1 before 2, and so forth). If you want to order elements a different
way, then specify a Comparator when you construct the set or map. Doing so gives you the
ability to govern precisely how elements are stored within sorted collections and maps.
The Comparator interface defined only two methods: compare( ) and equals( ). The compare(
) method, shown here, compares two elements for order:
int compare(T obj1, T obj2)
obj1 and obj2 are the objects to be compared. Normally, this method returns zero if the
objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative
value is returned.
The equals( ) method, shown here, tests whether an object equals the invoking comparator:
boolean equals(object obj)
Here, obj is the object to be tested for equality. The method returns true if obj and the
invoking object are both Comparator objects and use the same ordering. Otherwise, it returns
false.
You can obtain a comparator that reverses the ordering of the comparator on which it is
called by using reversed( ), shown here:
default Comparator<T> reversed( )
It returns the reverse comparator. For example, assuming a comparator that uses natural
ordering for the characters A through Z, a reverse order comparator would put B before A, C
before B, and so on. A method related to reversed( ) is reverseOrder( ).
Sandhya P N , Dept of CSE , CIT , Gubbi Page 31
BCS613D –Advanced JAVA
Using a Comparator
The following is an example that demonstrates the power of a custom comparator. It
implements the compare( ) method for strings that operates in reverse of normal. Thus,
it causes a tree set to be sorted in reverse order.
Output :
Look closely at the MyComp class, which implements Comparator by implementing
compare( ). Inside compare( ), the String method compareTo( ) compares the two strings.
However, bStr—not aStr—invokes compareTo( ).
This causes the outcome of the comparison to be reversed. Although the way in which the
reverse order comparator is implemented by the preceding program is perfectly adequate,
there is another way to approach a solution. It is now possible to simply call reversed( ) on a
natural-order comparator. It will return an equivalent comparator, except that it runs in
reverse
Sandhya P N , Dept of CSE , CIT , Gubbi Page 32
BCS613D –Advanced JAVA
The Collection Algorithms
The Collections Framework defines several algorithms that can be applied to collections and
maps. These algorithms are defined as static methods within the Collections class.
In Java, Collection algorithms refer to utility methods provided by the java.util.Collections
class that operate on collections such as lists, sets, and maps. These algorithms perform tasks
like sorting, searching, shuffling, and more.
Common Collection Algorithms in Java
The Collections class provides static methods that can be used directly without instantiating
the class.
List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3);
1 . Sorting
Collections.sort(List<T> list): Sorts a list in natural order (ascending for numbers,
lexicographical for strings).
Collections.sort(List<T> list, Comparator<? super T> c): Sorts a list using a custom
comparator.
Ex: Collections.sort(numbers);
2. Searching
Collections.binarySearch(List<T> list, T key):
Ex: int index = Collections.binarySearch(numbers, 3);
Searches for an element in a sorted list using binary search.
3. Shuffling
Collections.shuffle(List<T> list): Randomly rearranges elements.
Ex: Collections.shuffle(numbers);
4. Reversing
Collections.reverse(List<T> list): Reverses the order of elements.
Ex: Collections.reverse(numbers);
5. Finding Min and Max
Collections.min(Collection<T> coll): Finds the minimum element.
Collections.max(Collection<T> coll): Finds the maximum element.
Ex: int min = Collections.min(numbers);
int max = Collections.max(numbers);
6. Filling and Replacing Elements
Collections.fill(List<T> list, T obj): Replaces all elements with a specified object.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 33
BCS613D –Advanced JAVA
Collections.replaceAll(List<T> list, T oldVal, T newVal): Replaces occurrences of oldVal
with newVal.
Arrays
The Arrays class provides various static utility methods that are useful when working with
arrays. These methods help bridge the gap between collections and arrays. The asList( )
method returns a List that is backed by a specified array. In other words, both the list and the
array refer to the same location.
The binarySearch( ) method uses a binary search to find a specified value. This method
Sandhya P N , Dept of CSE , CIT , Gubbi Page 34
BCS613D –Advanced JAVA
must be applied to sorted arrays.
The copyOf( ) method returns a copy of an array.
The copyOfRange( ) method returns a copy of a range within an array.
The equals( ) method returns true if two arrays are equivalent. Otherwise, it returns
false.
The deepEquals( ) method can be used to determine if two arrays, which might contain
nested arrays, are equal.
The fill( ) method assigns a value to all elements in an array. In other words, it fills an
array with a specified value.
The sort( ) method sorts an array so that it is arranged in ascending order. One quite powerful
method in Arrays is parallelSort( ) because it sorts, into ascending order, portions of an array
in parallel and then merges the results. This approach can greatly speed up sorting times. Like
sort( ), there are two basic types of parallelSort( ), each with several overloads.
Arrays supports spliterators by including the spliterator( ) method. It has two basic forms.
The first type returns a spliterator to an entire array.
Another two methods are related: setAll( ) and parallelSetAll( ). Both assign values to all of
the elements, but parallelSetAll( ) works in parallel.
The three comparison methods to Arrays.
They are compare( ), compareUnsigned( ), and mismatch( ).
Each has several overloads and each has versions that let you define a range to compare. Here
is a brief description of each.
The compare( ) method compares two arrays. It returns zero if they are the same, a
positive value if the first array is greater than the second, and negative if the first array
is less than the second.
To perform an unsigned comparison of two arrays that hold integer values, use
compareUnsigned( ).
To find the location of the first mismatch between two arrays, use mismatch( ). It
returns the index of the mismatch, or −1 if the arrays are equivalent.
Arrays also provides toString( ) and hashCode( ) for the various types of arrays. In addition,
deepToString( ) and deepHashCode( ) are provided, which operate effectively on arrays that
contain nested arrays.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 35
BCS613D –Advanced JAVA
The following program illustrates how to use some of the methods of the Arrays class:
Sandhya P N , Dept of CSE , CIT , Gubbi Page 36
BCS613D –Advanced JAVA
The Legacy Classes and Interfaces
The legacy classes defined by java.util are shown here:
Dictionary
Hashtable
Properties
Stack
Vector
The Enumeration Interface
The Enumeration interface defines the methods by which you can enumerate (obtain one
at a time) the elements in a collection of objects. This legacy interface has been
superseded by Iterator. Although not deprecated, Enumeration is considered obsolete for
new code. However, it is used by several methods defined by the legacy classes (such as
Vector and Properties) .
The Enumeration interface in Java is a legacy interface that was introduced in JDK 1.0
and is used to iterate over collections, particularly older collection classes like Vector
and Hashtable.
When implemented, hasMoreElements( ) must return true while there are still more
elements to extract, and false when all the elements have been enumerated. nextElement(
) returns the next object in the enumeration. That is, each call to nextElement( ) obtains
the next object in the enumeration.
Vector
Vector implements a dynamic array that can grow or shrink in size. It is similar to ArrayList,
but with two differences:
Vector is synchronized, and it contains many legacy methods that duplicate the
functionality of methods defined by the Collections Framework.
Vector was reengineered to extend AbstractList and to implement the List interface.
Vector is fully compatible with collections, and a Vector can have its contents iterated
by the enhanced for loop.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 37
BCS613D –Advanced JAVA
Sandhya P N , Dept of CSE , CIT , Gubbi Page 38
BCS613D –Advanced JAVA
Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only
defines the default constructor, which creates an empty stack. Stack includes all the methods
defined by Vector and adds several of its own,
To put an object on the top of the stack, call push( ). To remove and return the top element,
call pop( ). You can use peek( ) to return, but not remove, the top object. The empty( )
method returns true if nothing is on the stack. The search( ) method determines whether an
object exists on the stack and returns the number of pops that are required to bring it to the
top of the stack.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 39
BCS613D –Advanced JAVA
An example that creates a stack, pushes several Integer objects onto it, and then pops them
off again:
Sandhya P N , Dept of CSE , CIT , Gubbi Page 40
BCS613D –Advanced JAVA
Dictionary
In Java, the Dictionary class is a part of the java.util package and is the legacy
implementation of a key-value pair data structure. It has been largely replaced by the
HashMap class, which is part of the Map interface. Given a key and value, you can store the
value in a Dictionary object. Once the value is stored, you can retrieve it by using its key.
Thus, like a map, a dictionary can be thought of as a list of key/value pairs. Although not
currently deprecated,
Hashtable
Hashtable is integrated into the Collections Framework. It is similar to HashMap, but is
synchronized. Like HashMap, Hashtable stores key/value pairs in a hash table. However,
neither keys nor values can be null. When using a Hashtable, you specify an object that is
used as a key, and the value that you want linked to that key. The key is then hashed, and the
resulting hash code is used as the index at which the value is stored within the table.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 41
BCS613D –Advanced JAVA
Example : Creating Hashtable , accesing elements and removing elements
Sandhya P N , Dept of CSE , CIT , Gubbi Page 42
BCS613D –Advanced JAVA
Properties
Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is
a String and the value is also a String. The Properties class is used by some other Java
classes.
For example, it is the type of object returned by System.getProperties( ) when obtaining
environmental values.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 43
BCS613D –Advanced JAVA
Enumeration and Iterator Comparison
Using store( ) and load( )
One of the most useful aspects of Properties is that the information contained in a Properties
object can be easily stored to or loaded from disk with the store( ) and load( ) methods. At
any time, you can write a Properties object to a stream or read it back. This makes property
lists especially convenient for implementing simple databases.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 44
BCS613D –Advanced JAVA
Parting Thoughts on Collections
The Collections Framework gives you, the programmer, a powerful set of well-engineered
solutions to some of programming’s most common tasks. Consider using a collection the
next time you need to store and retrieve information. Remember, collections need not be
reserved for only the “large jobs,” such as corporate databases, mailing lists, or inventory
systems. They are also effective when applied to smaller jobs. For example, a TreeMap might
make an excellent collection to hold the directory structure of a set of files. A TreeSet could
be quite useful for storing project-management information.
Sandhya P N , Dept of CSE , CIT , Gubbi Page 45