0% found this document useful (0 votes)
4 views49 pages

Advanced Java Module-1

The document provides an overview of the Java Collections Framework, detailing its purpose, structure, and key interfaces such as Collection, List, Set, Queue, and Deque. It explains the functionalities of various classes like ArrayList and LinkedList, highlighting their methods and use cases. The document emphasizes the framework's design goals of high performance, interoperability, and ease of extension.

Uploaded by

Goodperson CoDM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views49 pages

Advanced Java Module-1

The document provides an overview of the Java Collections Framework, detailing its purpose, structure, and key interfaces such as Collection, List, Set, Queue, and Deque. It explains the functionalities of various classes like ArrayList and LinkedList, highlighting their methods and use cases. The document emphasizes the framework's design goals of high performance, interoperability, and ease of extension.

Uploaded by

Goodperson CoDM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Module-1

The Collections and


Framework
Advanced Java (BIS402)

Java.util Package
• This java.util package contains a large assortment of classes and interfaces that
support a broad range of functionality. For example, java.util has classes that
generate pseudorandom numbers, manage date and time, observe events,
manipulate sets of bits, tokenize strings, and handle formatted data.
• The java.util package also contains one of Java’s most powerful subsystems: the
Collections Framework. The Collections Framework is a sophisticated hierarchy
of interfaces and classes that provide state-of-the-art technology for managing
groups of objects.
• Because java.util contains a wide array of functionality, it is quite large. Here is a
list of its top-level classes:

2
Collections Framework

• The Collections Framework was designed to meet several goals.


• First, the framework had to be high-performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are
highly efficient. You seldom, if ever, need to code one of these “data engines”
manually.
• Second, the framework had to allow different types of collections to work in a
similar manner and with a high degree of interoperability.
• Third, extending and/or adapting a collection had to be easy. Toward this end,
the entire Collections Framework is built upon a set of standard interfaces.
Several standard implementations (such as LinkedList, HashSet, and TreeSet) of
these interfaces are provided that you may use as-is.
• Finally, mechanisms were added that allow the integration of standard arrays
into the Collections Framework.
• Any group of individual objects which are represented as a single unit is known
as the collection of the objects. In Java, a separate framework named the
“Collection Framework” has been defined in JDK 1.2 which holds all the
collection classes and interface in it.
• The Collection interface (java.util.Collection) and Map interface (java.util.Map)
are the two main “root” interfaces of Java collection classes.
Advanced Java (BIS402) 4
Collections Framework
• A framework is a set of classes and interfaces which provide a ready-made
architecture. In order to implement a new feature or a class, there is no need to
define a framework.

Advanced Java (BIS402) 5

The Collection Interfaces


The Collections Framework defines several core interfaces. This section
provides an overview of each interface. Beginning with the collection
interfaces is necessary because they determine the fundamental nature of
the collection classes. Put differently, the concrete classes simply provide
different implementations of the standard interfaces. The interfaces that
underpin collections are summarized in the following table

Advanced Java (BIS402) 6


The Collection Interfaces
• Collection is a generic interface that has this
declaration:
interface Collection<E>
E specifies the type of objects that the collection will
hold.
• Collection extends the Iterable interface.
• Objects are added to a collection by calling add( ).
• You can add the entire contents of one collection
to another by calling addAll( ).

Advanced Java (BIS402) 7

Advanced Java (BIS402) 8


Advanced Java (BIS402) 9

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, declaration:
interface List<E>
• Here, E specifies the type of objects that the list
will hold.
Advanced Java (BIS402) 10
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, declaration:
interface List<E>
• Here, E specifies the type of objects that the list will hold.

//Creating a List of type String using ArrayList


List<String> list=new ArrayList<String>();

//Creating a List of type Integer using ArrayList


List<Integer> list=new ArrayList<Integer>();

//Creating a List of type Book using ArrayList


List<Book> list=new ArrayList<Book>();

//Creating a List of type String using LinkedList


List<String> list=new LinkedList<String>();
Advanced Java (BIS402) 11

Advanced Java (BIS402)


import java.util.*;
public class ListExample1{
public static void main(String args[]){
//Creating a List
List<String> list=new ArrayList<String>();

//Adding elements in the List


list.add("Mango");
list.add("Apple");
list.add("Banana");
list.add("Grapes");

//Iterating the List element using for-each loop


for(String fruit:list)
System.out.println(fruit);
}
}
Advanced Java (BIS402) 13

/* convert Array to List */


import java.util.*;
public class ArrayToListExample{
public static void main(String args[]){
//Creating Array
String[] arr={"Java","Python","PHP","C++"};
System.out.println("Printing Array: "+Arrays.toString(arr));

//Converting Array to List


List<String> list=new ArrayList<String>();
for(String lang:arr){
list.add(lang);
}
System.out.println("Printing List: "+list);
}
}

Advanced Java (BIS402) 14


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.
• 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
• There are two interfaces that extend the set
implementation namely SortedSet and NavigableSet.

Advanced Java (BIS402) 15

16
Advanced Java (BIS402)
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.

Advanced Java (BIS402) 17

Advanced Java (BIS402)


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

Advanced Java (BIS402) 19

20
Advanced Java (BIS402)

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:
interface Queue<E>
• Here, E specifies the type of objects that the queue will hold
• Several methods throw a ClassCastException when an object is
incompatible with the elements in the queue.
• A NullPointerException is thrown if an attempt is made to
store a null object and null elements are not allowed in the
queue.
• An IllegalArgumentException is thrown if an invalid argument
is used.
• An IllegalStateException is thrown if an attempt is made to
add an element to a fixed-length queue that is full.
• A NoSuchElementException is thrown if an attempt is made to
remove an element from an empty queue.

Advanced Java (BIS402) 22


Despite its simplicity, Queue offers several points of interest.
• First, elements can only be removed from the head of the queue.
• Second, there are two methods that obtain and remove elements: poll( )
and remove( ). The difference between them is that poll( ) returns null if the
queue is empty, but remove( ) throws an exception.
• Third, there are two methods, element( ) and peek( ), that obtain but don’t
remove the element at the head of the queue. They differ only in that
element( ) throws an exception if the queue is empty, but peek( ) returns
null. Finally, notice that offer( ) only attempts to add an element to a queue.
Because some queues have a fixed length and might be full, offer( ) can
fail.

Advanced Java (BIS402) 23

Advanced Java (BIS402)


24
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, first-out 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 18-6.

Advanced Java (BIS402) 25

Advanced Java (BIS402) 26


Advanced Java (BIS402)
27

The Collection Classes


• Some of the classes provide full implementations that can be
used as-is. Others are abstract, providing skeletal
implementations that are used as starting points for creating
concrete collections.

Advanced Java (BIS402) 28


ArrayList
• 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. 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.
• 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
anarray list.

Advanced Java (BIS402) 29

import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();

list.add("Mango");//Adding object in arraylist


list.add("Apple");
list.add("Banana");
list.add("Grapes");

//Printing the arraylist object


System.out.println(list);
}
}
OUTPUT
[Mango, Apple, Banana, Grapes]

Advanced Java (BIS402) 30


Get and Set ArrayList
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));
al.set(1,"Dates");

//Traversing list Output:


Returning element: Apple
for(String fruit:al) Mango
System.out.println(fruit); Dates
} Banana
} Grapes

Advanced Java (BIS402) 31

// Demonstrate ArrayList.
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
// Create an array list.
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +al.size());
// Add elements to the array list.
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +al.size());
// Display the array list.
System.out.println("Contents of al: " + al);
// Remove elements from the array list.
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +al.size());
System.out.println("Contents of al: " + al);
}
}

Advanced Java (BIS402) 32


Collections.sort(list2)
import java.util.*;
class SortArrayList{
public static void main(String args[]){
//Creating a list of fruits
List<String> list1=new ArrayList<String>();
list1.add("Mango");
list1.add("Apple");
list1.add("Banana");
list1.add("Grapes");
//Sorting the list
Collections.sort(list1); Output:
//Traversing list through the for-each loop Apple
for(String fruit:list1) Banana
System.out.println(fruit); Grapes
Mango
}
}

Advanced Java (BIS402) 33

Iterator
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Output:
Iterator itr=list.iterator(); Mango
while(itr.hasNext()){ Apple
System.out.println(itr.next()); Banana
Grapes
}
}
}
Advanced Java (BIS402) 34
Obtaining an Array from an ArrayList
When working with ArrayList, we will sometimes want to obtain an actual array that
contains the contents of the list. We can do this by calling toArray( ), which is
defined by Collection.
Several reasons exist why we 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
Whatever the reason, converting an ArrayList to an array is a trivial matter. There
are two versions of toArray( ),
object[ ] toArray( )
<T> T[ ] toArray(T array[ ])
The first returns an array of Object. The second returns an array of elements that
have the same type as T.

Advanced Java (BIS402) 35

// Convert an ArrayList into an array.


import java.util.*;
class ArrayListToArray {
public static void main(String args[]) {
// Create an array list.
ArrayList<Integer> al = new ArrayList<Integer>();
// Add elements to the array list.
al.add(1);
al.add(2);
al.add(3);
al.add(4);
System.out.println("Contents of al: " + al);
// Get the array.
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
// Sum the array.
for(int i : ia)
sum += i;
System.out.println("Sum is: " + sum);
}
}
Advanced Java (BIS402) 36
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, we 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( )
Advanced Java (BIS402) 37

Advanced Java (BIS402)


38
HashSet Class
• 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.
• 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—we
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.
• The following constructors are defined:
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
HashSet(int capacity, float fillRatio)
Advanced Java (BIS402) 39

• The first form constructs a default hash set.


• The second form initializes the hash set by using the elements of c.
• The third form initializes the capacity of the hash set to capacity. (The default
capacity is 16.)
• The fourth form initializes both the capacity and the fill ratio (also called load
capacity ) of the hash set from its arguments. The fill ratio must be between 0.0
and 1.0, and it determines how full the hash set can be before it is resized
upward.

Advanced Java (BIS402) 40


LinkedHashSet Class
• 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.
• LinkedHashSet maintains a linked list of the entries in the set, in the order in
which they were inserted. This allows insertion-order iteration over the set.
That is, when cycling through a LinkedHashSet using an iterator, the
elements will be returned in the order in which they were inserted. This is
also the order in which they are contained in the string returned by toString(
) when called on a LinkedHashSet object.
• To see the effect of LinkedHashSet, try substituting LinkedHashSet for
HashSet in the preceding program.
• The output will be [Beta, Alpha, Eta, Gamma, Epsilon, Omega] which is the
order in which the elements were inserted.

Advanced Java (BIS402) 41

Advanced Java (BIS402)


import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Output:
103 Rahul
102 Ravi
101 Vijay
Advanced Java (BIS402) 100 Amit 43

TreeSet class
• TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a
collection that uses a tree for storage. Objects are stored in sorted, ascending order.
• Access and retrieval times are quite fast, which makes TreeSet an excellent choice
when storing large amounts of sorted information that must be found quickly.
• TreeSet is a generic class that has this declaration:
class TreeSet<E>
• Here, E specifies the type of objects that the set will hold.
• TreeSet has the following constructors:
TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)
• The first form constructs an empty tree set that will be sorted in ascending order
according to the natural order of its elements.
• The second form builds a tree set that contains the elements of c.
• The third form constructs an empty tree set that will be sorted according to the
comparator specified by comp.
• The fourth form builds a tree set that contains the elements of ss
Advanced Java (BIS402) 44
// Demonstrate TreeSet.
import java.util.*;
class TreeSetDemo {
public static void main(String args[]) {
// Create a tree set.
TreeSet<String> ts = new TreeSet<String>();
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
System.out.println(ts.subSet("C", "F"));
}
}

Advanced Java (BIS402) 45

PriorityQueue Class
• PriorityQueue extends AbstractQueue and implements the Queue interface. It creates a
queue that is prioritized based on the queue’s comparator.
• PriorityQueue is a generic class that has this declaration:
class PriorityQueue<E>
• Here, E specifies the type of objects stored in the queue. PriorityQueues are dynamic, growing
as necessary.
• PriorityQueue defines the six constructors shown here:
PriorityQueue( )
PriorityQueue(int capacity)
PriorityQueue(Comparator<? super E> comp) (Added by JDK 8.)
PriorityQueue(int capacity, Comparator<? super E> comp)
PriorityQueue(Collection<? extends E> c)
PriorityQueue(PriorityQueue<? extends E> c)
PriorityQueue(SortedSet<? extends E> c)
• The first constructor builds an empty queue. Its starting capacity is 11.
• The second constructor builds a queue that has the specified initial capacity.
• The third constructor specifies a comparator, and the fourth builds a queue with the specified
capacity and comparator.
• The last three constructors create queues that are initialized with the elements of the
collection passed in c. In all cases, the capacity grows automatically as elements are added
• If no comparator is specified when a PriorityQueue is constructed, then the default
comparator for the type of data stored in the queue is used. The default comparator will order
the Aq du veaunec ei nd aJsacvean (dBi nI Sg 4o0r2d) e r . 46
Advanced Java (BIS402)
47

The ArrayDeque Class


• The ArrayDeque in Java provides a way to apply resizable-array in addition to the implementation
of the Deque interface. It is also known as Array Double Ended Queue or Array Deck. This is a
special kind of array that grows and allows users to add or remove an element from both sides of
the queue.
• Null elements are prohibited in the ArrayDeque.
• The ArrayDeque class extends AbstractCollection and implements the Deque interface. It adds no
methods of its own.
• ArrayDeque creates a dynamic array and has no capacity restrictions. (The Deque interface
supports implementations that restrict capacity, but does not require such restrictions.)
ArrayDeque is a generic class that has this declaration:
class ArrayDeque<E>
• Here, E specifies the type of objects stored in the collection.
• ArrayDeque defines the following constructors:
ArrayDeque( )
ArrayDeque(int size)
ArrayDeque(Collection<? extends E> c)
• The first constructor builds an empty deque. Its starting capacity is 16.
• The second constructor builds a deque that has the specified initial capacity.
• The third constructor creates a deque that is initialized with the elements of the collection passed
in c. In all cases, the capacity grows as needed to handle the elements added to the deque.

Advanced Java (BIS402) 48


Advanced Java (BIS402) 49

The EnumSet Class


• EnumSet extends AbstractSet and implements Set. It is specifically
for use with elements of an enum type.
• It is a generic class that has this declaration:
class EnumSet<E extends Enum<E>>
• Here, E specifies the elements.
• Notice that E must extend Enum<E>, which enforces the
requirement that the elements must be of the specified enum
type.
• EnumSet defines no constructors. Instead, it uses the factory
methods to create objects.
• All methods can throw NullPointerException.
• The copyOf( ) and range( ) methods can also throw
IllegalArgumentException.
• Notice that the of( ) method is overloaded a number of times.

Advanced Java (BIS402) 50


Advanced Java (BIS402) 51

Advanced Java (BIS402) 52


The Iterable Interfaces
• The Iterable interface was introduced in JDK 1.5. In general, an object Implementing Iterable allows it to
be iterated. An iterable interface allows an object to be the target of enhanced for loop(for-each loop).
Definition of Iterable
public interface Iterable<T> {
Iterator<T> iterator();
Spliterator<T> spliterator();
void forEach(Consumer<? super T> action); }
Here, T is the type of element returned by the Iterator.

Ways of Iterating
There are three ways in which objects of Iterable can be iterated.
1. Using enhanced for loop(for-each loop)
2. Using Iterable forEach loop
3. Using Iterator<T> interface

Using an Iterator
Before you can access a collection through an iterator, you must obtain one. Each of the collection classes
provides an iterator( ) method that returns an iterator to the start of the collection. By using this iterator object,
you can access each element in the collection, one element at a time. 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( ).
Advanced Java (BIS402) 53

Advanced Java (BIS402) 54


Using an Iterator

// Demonstrate iterators. // Modify objects being iterated.


import java.util.*; ListIterator<String> litr = al.listIterator();
class IteratorDemo { while(litr.hasNext()) {
public static void main(String args[]) { String element = litr.next();
// Create an array list. litr.set(element + "+");
}
ArrayList<String> al = new ArrayList<String>();
System.out.print("Modified contents of al: ");
// Add elements to the array list. itr = al.iterator();
al.add("C"); while(itr.hasNext()) {
al.add("A"); String element = itr.next();
al.add("E"); System.out.print(element + " ");
al.add("B"); }
al.add("D"); System.out.println();
al.add("F"); // Now, display the list backwards.
System.out.print("Modified list backwards: ");
// Use iterator to display contents of al. while(litr.hasPrevious()) {
System.out.print("Original contents of al: "); String element = litr.previous();
Iterator<String> itr = al.iterator(); System.out.print(element + " ");
while(itr.hasNext()) { }
String element = itr.next(); System.out.println();
System.out.print(element + " "); }
}
}
The output is shown here:
System.out.println(); Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
Advanced Java (BIS402) 55

The For-Each Alternative to Iterators


The for can cycle through any collection of objects that implement the Iterable
interface. Because all of the collection classes implement this interface, they can all
be operated upon by the for. // Use the for-each for loop to cycle through a collection.
import java.util.*;
class ForEachDemo {
public static void main(String args[]) {
// Create an array list for integers.
ArrayList<Integer> vals = new ArrayList<Integer>();
// Add values to the array list.
vals.add(1);
vals.add(2);
vals.add(3);
vals.add(4);
vals.add(5);
// Use for loop to display the values.
System.out.print("Contents of vals: ");
for(int v : vals)
System.out.print(v + " ");
System.out.println();
// Now, sum the values by using a for loop.
int sum = 0;
for(int v : vals)
sum += v;
System.out.println("Sum of values: " + sum);
}
}
The output from the program is shown here:
Advanced Java (BIS402) Contents of vals:1 2 3 4 5l 56
Sum of values: 15
Spliterators
Like Iterator and ListIterator, Spliterator is a Java Iterator, which is used to iterate
elements one-by-one from a List implemented object. Some important points about Java
Spliterator are:
• Java Spliterator is an interface in Java Collection API.
• Spliterator is introduced in Java 8 release in java.util package.
• It supports Parallel Programming functionality.
• We can use it for both Collection API and Stream API classes.
• It provides characteristics about Collection or API objects.
• We can NOT use this Iterator for Map implemented classes.
• It uses tryAdvance() method to iterate elements individually in multiple Threads to
support Parallel Processing.
• It uses forEachRemaining() method to iterate elements sequentially in a single
Thread.
• It uses trySplit() method to divide itself into Sub-Spliterators to support Parallel
Processing.
• Spliterator supports both Sequential and Parallel processing of data.
Spliterator itself does not provide the parallel programming behavior. However, it
provides some methods to support it. Developers should utilize Spliterator interface
methods and implement parallel programming by using Fork/Join Framework (one good
a
AdpvparnocaecdhJ)a. va (BIS402)
57

Advanced Java (BIS402) 58


// A simple Spliterator demonstration.
import java.util.*;
class SpliteratorDemo {
public static void main(String args[]) {
// Create an array list for doubles.
ArrayList<Double> vals = new ArrayList<>();
// Add values to the array list.
vals.add(1.0);
vals.add(2.0);
vals.add(3.0);
vals.add(4.0);
vals.add(5.0);
// Use tryAdvance() to display contents of vals.
System.out.print("Contents of vals:\n");
Spliterator<Double> spltitr = vals.spliterator();
while(spltitr.tryAdvance((n) -> System.out.println(n)));
System.out.println();
// Create new list that contains square roots.
spltitr = vals.spliterator();
ArrayList<Double> sqrs = new ArrayList<>();
while(spltitr.tryAdvance((n) -> sqrs.add(Math.sqrt(n))));
// Use forEachRemaining() to display contents of sqrs.
System.out.print("Contents of sqrs:\n");
spltitr = sqrs.spliterator();
spltitr.forEachRemaining((n) -> System.out.println(n));
System.out.println();
Adv}anced Java (BIS402) 59
}

Storing User-Defined Classes in Collections


// A simple mailing list example.
import java.util.*;
class Address {
private String name;
private String street;
private String city;
private String state;
private String code;
Address(String n, String s, String c, String st, String cd) {
name = n;
street = s;
city = c;
The output from the program
state = st;
code = cd; }
is shown here:
public String toString() { J.W. West
return name + "\n" + street + "\n" + city + " " + state + " " + code; } 11 Oak Ave
} Urbana IL 61801
class MailList {
public static void main(String args[]) { Ralph Baker
LinkedList<Address> ml = new LinkedList<Address>(); 1142 Maple Lane
// Add elements to the linked list. Mahomet IL 61853
ml.add(new Address("J.W. West", "11 Oak Ave","Urbana", "IL", "61801"));
ml.add(new Address("Ralph Baker", "1142 Maple Lane","Mahomet", "IL", Tom Carlton
"61853")); 867 Elm St
ml.add(new Address("Tom Carlton", "867 Elm St","Champaign", "IL", "61820"));
Champaign IL 61820
// Display the mailing list.
for(Address element : ml)
System.out.println(element + "\n");
AdvSaynstceemd.oJuatv.pari(nBtlInS()4; 02) 60
} }
Map Interfaces
• A map is an object that stores associations between keys and values, or key/value
pairs. Given a key, we 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.

Advanced Java (BIS402) 61

The Map Interface


• The Map interface maps unique keys to values. A key is an object that you use to retrieve a value.
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.
• Map is generic and is declared as shown here:
interface Map<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.
• Several methods throw a ClassCastException when an object is incompatible with the elements in
a map.
• A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed
in the map. An UnsupportedOperationException is thrown when an attempt is made to change an
unmodifiable map.
• An IllegalArgumentException is thrown if an invalid argument is used.
• 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.
• As mentioned earlier, although part of the Collections Framework, maps are not, themselves,
collections because they do not implement the Collection interface. However, we can obtain a
collection-view of a map. To do this, you can use the entrySet( ) method. It returns a Set that
contains the elements in the map. To obtain a collection-view of the keys, use keySet( ).
• To get a collection-view of the values, use values( ). For all three collection- views, the collection is
backed by the map. Changing one affects the other. Collection-views are the means by which
maps are integrated into the larger Collections Framework.
Advanced Java (BIS402) 62
Advanced Java (BIS402)
63

Advanced Java (BIS402)


64
Advanced Java (BIS402)

The SortedMap Interface


• The SortedMap interface extends Map. It ensures that the entries are maintained in ascending
order based on the keys. SortedMap is generic and is declared as shown here:
interface SortedMap<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.

Advanced Java (BIS402) 66


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.
NavigableMap is a generic
interface that has this
declaration:
interface NavigableMap<K,V>
Here, K specifies the type of
the keys, and V specifies the
type of the values associated
with
the keys. In addition to the
methods that it inherits from
SortedMap, NavigableMap
adds those summarized in
Table 18-13.

Advanced Java (BIS402)

The Map Classes


• Several classes provide implementations of the map interfaces. Notice that AbstractMap is a
superclass for all concrete map implementations.
• WeakHashMap implements a map that uses “weak keys,” which allows an element in a map to be
garbage-collected when its key is otherwise unused.

Advanced Java (BIS402) 68


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. HashMap is a generic class that has this declaration:
class HashMap<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.
• The following constructors are defined:
HashMap( )
HashMap(Map<? extends K, ? extends V> m)
HashMap(int capacity)
HashMap(int capacity, float fillRatio)
• The first form constructs a default hash map.
• The second form initializes the hash map by using the elements of m.
• The third form initializes the capacity of the hash map to capacity.
• The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments. The
meaning of capacity and fill ratio is the same as for HashSet, described earlier. The default capacity is
16. The default fill ratio is 0.75
• HashMap implements Map and extends AbstractMap. It does not add any methods of its own.

Advanced Java (BIS402) 69

Advanced Java (BIS402) 70


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.
• TreeMap is a generic class that has this declaration:
class TreeMap<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.
• The following TreeMap constructors are defined:
TreeMap( )
TreeMap(Comparator<? super K> comp)
TreeMap(Map<? extends K, ? extends V> m)
TreeMap(SortedMap<K, ? extends V> sm)
• The first form constructs an empty tree map that will be sorted by using the natural order
• of its keys.
• The second form constructs an empty tree-based map that will be sorted by using
• the Comparator comp.
• The third form initializes a tree map with the entries from m, which will be sorted by using the
natural order of the keys.
• The fourth form initializes a tree map with the entries from sm, which will be sorted in the same
order as sm.
• TreeMap has no map methods beyond those specified by the NavigableMap interface and the
AbstractMap class.
Advanced Java (BIS402) 71

Advanced Java (BIS402) 72


The Linked HashMap Class
• LinkedHashMap extends HashMap. It maintains a linked list of the entries in the map, in the order in which they
were inserted. This allows insertion-order iteration over the map. That is, when iterating through a collection-
view of a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also
create a LinkedHashMap that returns its elements in the order in which they were last accessed.
• LinkedHashMap is a generic class that has this declaration:
class LinkedHashMap<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.
• LinkedHashMap defines the following constructors:
LinkedHashMap( )
LinkedHashMap(Map<? extends K, ? extends V> m)
LinkedHashMap(int capacity)
LinkedHashMap(int capacity, float fillRatio)
LinkedHashMap(int capacity, float fillRatio, boolean Order)
• The first form constructs a default LinkedHashMap.
• The second form initializes the LinkedHashMap with the elements from m.
• The third form initializes the capacity.
• The fourth form initializes both capacity and fill ratio. The meaning of capacity and fill ratio are
• the same as for HashMap. The default capacity is 16. The default ratio is 0.75.
• The last form allows you to specify whether the elements will be stored in the linked list by insertion order, or
by order of last access. If Order is true, then access order is used. If Order is false,then insertion order is used.
• LinkedHashMap adds only one method to those defined by HashMap. This method is removeEldestEntry( ), and
it is shown here:
• protected boolean removeEldestEntry(Map.Entry<K, V> e)
• This method is called by put( ) and putAll( ). The oldest entry is passed in e. By default, this method returns false
and does nothing. However, if you override this method, then you can have the LinkedHashMap remove the
oldest entry in the map. To do this, have your override return true. To keep the oldest entry, return false
Advanced Java (BIS402) 73

The IdentityHashMap and EnumMap Class


• IdentityHashMap extends AbstractMap and implements the Map interface. It is similar to
HashMap except that it uses reference equality when comparing elements. IdentityHashMap is a
generic class that has this declaration:
class IdentityHashMap<K, V>
• Here, K specifies the type of key, and V specifies the type of value.

• EnumMap extends AbstractMap and implements Map. It is specifically for use with keys of an
enum type. It is a generic class that has this declaration:
class EnumMap<K extends Enum<K>, V>
• Here, K specifies the type of key, and V specifies the type of value. Notice that K must extend
Enum<K>, which enforces the requirement that the keys must be of an enum type.
• EnumMap defines the following constructors:
EnumMap(Class<K> kType)
EnumMap(Map<K, ? extends V> m)
EnumMap(EnumMap<K, ? extends V> em)
• The first constructor creates an empty EnumMap of type kType.
• The second creates an EnumMap map that contains the same entries as m.
• The third creates an EnumMap initialized with the values in em.
• EnumMap defines no methods of its own.

Advanced Java (BIS402) 74


The Comparator Interface
• 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.
• 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.
• Comparator is a generic interface that has this declaration:
interface Comparator<T>
• Prior to JDK 8, the Comparator interface defined only two methods: compare( ) and equals( ).

Advanced Java (BIS402) 75

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 method can
throw a ClassCastException if the types of the objects are not compatible for comparison.

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.

We 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.

A method related to reversed( ) is reverseOrder( ), shown next:


static <T extends Comparable<? super T>> Comparator<T> reverseOrder( )
It returns a comparator that reverses the natural order of the elements.

We can obtain a comparator that uses natural ordering by calling the static method naturalOrder( ), shown next:
static <T extends Comparable<? super T>> Comparator<T> naturalOrder( )

If you want a comparator that can handle null values, use nullsFirst( ) or nullsLast( ), shown here:
static <T> Comparator<T> nullsFirst(Comparator<? super T> comp)
static <T> Comparator<T> nullsLast(Comparator<? super T> comp)
The nullsFirst( ) method returns a comparator that views null values as less than other values. The nullsLast( )
method returns a comparator that views null values as greater than other values. In both cases, if the two
values being compared are non-null, comp performs the comparison. If comp is passed null, then all non-null
v a l uAe ds vaar nec vei de wJ ae vd aa (sB eI Sq 4u 0i v2a) l e n t .
76
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.
// Use a custom comparator.
Method1
import java.util.*; Method 2
// A reverse comparator for strings. class CompDemo2 {
class MyComp implements Comparator<String> { public static void main(String args[]) {
public int compare(String aStr, String bStr) { // Pass a reverse comparator to TreeSet() via a
// Reverse the comparison. // lambda expression.
return bStr.compareTo(aStr); TreeSet<String> ts = new TreeSet<String>(
} (aStr, bStr) -> bStr.compareTo(aStr));
// No need to override equals or the default methods. // Add elements to the tree set.
} ts.add("C");
class CompDemo { ts.add("A");
public static void main(String args[]) { ts.add("B");
// Create a tree set. ts.add("E");
TreeSet<String> ts = new TreeSet<String>(new MyComp()); ts.add("F");
// Add elements to the tree set. ts.add("D");
ts.add("C"); // Display the elements.
ts.add("A"); for(String element : ts)
ts.add("B"); System.out.print(element + " ");
ts.add("E"); System.out.println();
ts.add("F"); }
you can use the following sequence to create a
ts.add("D"); TreeSet that orders its string
// Display the elements. elements in reverse:
for(String element : ts) MyComp mc = new MyComp(); // Create a
System.out.print(element + " "); comparator
System.out.println(); // Pass a reverse order version of MyComp to
} } TreeSet.
As the following output shows, the tree is now sorted in reverse order: TreeSet<String> ts = new
F EAD dvCanBcAed Java (BIS402) TreeSet<String>(mc.reversed());
77

Beginning with JDK 8, it is not actually necessary to create the MyComp class in the preceding examples
because a lambda expression can be easily used instead. For example, you can remove the MyComp class
entirely and create the string comparator by using this statement:

// Use a lambda expression to implement Comparator<String>.


Comparator<String> mc = (aStr, bStr) -> aStr.compareTo(bStr);

One other point: in this simple example, it would also be possible to specify a reverse comparator via a
lambda expression directly in the call to the TreeSet( ) constructor, as shown here:
// Pass a reversed comparator to TreeSet() via a lambda expression.
TreeSet<String> ts = new TreeSet<String>( (aStr, bStr) -> bStr.compareTo(aStr));

By making these changes, the program is substantially shortened, as its final version shown
here illustrates:
// Use a lambda expression to create a reverse comparator.
import java.util.*;
class CompDemo2 {
public static void main(String args[]) {
// Pass a reverse comparator to TreeSet() via a lambda expression.
TreeSet<String> ts = new TreeSet<String>( (aStr, bStr) -> bStr.compareTo(aStr));
// Add elements to the tree set.
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
// Display the elements.
for(String element : ts)
System.out.print(element + " ");
SysAtedmv.aon
ut.
cpredinJtlna(v);a (BIS402)
} 78
The Collections Algorithms

Advanced Java (BIS402)

Advanced Java (BIS402) 80


Advanced Java (BIS402) 81

The Legacy Classes and Interfaces


• When collections were added, several of the original classes were reengineered to support
the collection interfaces. Thus, they are now technically part of the Collections Framework.
However, where a modern collection duplicates the functionality of a legacy class, you will
usually want to use the newer collection class.
• In general, the legacy classes are supported because there is still code that uses them. One
other point: none of the modern collection classes described in this chapter are synchronized,
but all the legacy classes are synchronized. This distinction may be important in some
situations. Of course, you can easily synchronize collections by using one of the algorithms
provided by Collections.

Advanced Java (BIS402) 82


The Legacy Classes and Interfaces: 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
• It is used by several methods defined by the legacy classes (such as Vector and Properties)
and is used by several other API classes. Because it is still in use, it was retrofitted for
generics by JDK 5. It has this declaration:
interface Enumeration<E>
• where E specifies the type of element being enumerated.
• Enumeration specifies the following two methods:
boolean hasMoreElements( )
E nextElement( )
• 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.
• It throws NoSuchElementException when the enumeration is
• complete.

Advanced Java (BIS402) 83

The Legacy Classes and Interfaces: Vector


• Vector implements a dynamic array. 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.
• With the advent of collections, Vector was reengineered to extend AbstractList and to
implement the List interface. With the release of JDK 5, it was retrofitted for generics and
reengineered to implement Iterable.
• This means that Vector is fully compatible with collections, and a Vector can have its contents
iterated by the enhanced for loop.
• Vector is declared like this:
class Vector<E>
• Here, E specifies the type of element that will be stored.
• Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection<? extends E> c)
• Vector defines these protected data members:
int capacityIncrement;
int elementCount;
Object[ ] elementData;
The increment value is stored in capacityIncrement. The number of elements currently in the
vector is stored in elementCount. The array that holds the vector is stored in elementData.
Advanced Java (BIS402) 84
In addition to the collections methods specified by List, Vector defines several
legacy methods

85
Advanced Java (BIS402)

86

Advanced Java (BIS402)


The Legacy Classes and Interfaces: 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. With the release of JDK 5,
Stack was retrofitted for generics and is declared as shown here:
class Stack<E>
• Here, E specifies the type of element stored in the stack

Advanced Java (BIS402) 87

Advanced Java (BIS402) 88


The Legacy Classes and Interfaces: Dictionary
• Dictionary is an abstract class that represents a key/value storage repository and operates
much like Map. 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.
• With the advent of JDK 5, Dictionary was made generic. It is declared as shown here:
class Dictionary<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.

Advanced Java (BIS402) 89

The Legacy Classes and Interfaces: Hashtable


• 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.
• Hashtable was made generic by JDK 5. It is declared like this:
class Hashtable<K, V>
• Here, K specifies the type of keys, and V specifies the type of values.
• The Hashtable constructors are shown here:
Hashtable( )
Hashtable(int size)
Hashtable(int size, float fillRatio)
Hashtable(Map<? extends K, ? extends V> m)

Advanced Java (BIS402) 90


Advanced Java (BIS402) 91

Advanced Java (BIS402) 92


The Legacy Classes and Interfaces: 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. Although the
Properties class, itself, is not generic, several of its methods are.
• Properties defines these constructors:
Properties( )
Properties(Properties propDefault)
• The first version creates a Properties object that has no default values.
• The second creates an object that uses propDefault for its default values

Advanced Java (BIS402) 93

Advanced Java (BIS402) 94


// Demonstrate a Property list.
import java.util.*;
class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
capitals.put(“Karnataka", “Bengaluru");
capitals.put(“Kerala", “Thiruvananthapuram");
capitals.put("Madhya Pradesh", “Bhopal");
capitals.put(“Rajasthan", “Jaipur");
capitals.put(“Tamilnadu", “Chennai");
// Get a set-view of the keys.
Set<?> states = capitals.keySet();
// Show all of the states and capitals.
for(Object name : states)
System.out.println("The capital of " + name + " is " + capitals.getProperty((String)name) + ".");
System.out.println();
// Look for state not in list -- specify default.
String str = capitals.getProperty(“Punjab", "Not Found");
System.out.println("The capital of Punjab is " + str + ".");
}
}

Advanced Java (BIS402) 95

Advanced Java (BIS402) 96

You might also like