Advanced Java Module-1
Advanced Java Module-1
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
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.
20
Advanced Java (BIS402)
import java.util.*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
// 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);
}
}
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.
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"));
}
}
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
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
• 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.
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.
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:
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
• 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.
85
Advanced Java (BIS402)
86
• 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
• 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