Here are some of the features and enhancements in jdk1.6. And we will explore them further in this chapter:
Only important features we need for interview all other features you will understand as you get experience in industry.
“The collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. It reduces programming effort while increasing performance.
It allows for interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software reuse.”
These new collection interfaces provided:
Here is a list of topics that will be covered in this chapter:
java.util.ArrayDeque
java.util.LinkedList
To create a Deque instance, following the steps given below:
Deque dequeA = new LinkedList ();
Deque dequeB = new ArrayDeque ();
Deque dequeA = new LinkedList();
dequeA.add("element 1"); //add element at tail
dequeA.addFirst("element 2"); //addelement at head
dequeA.addLast ("element 3"); //addelement at tail
Object firstElement = dequeA.element(); //retrieves but does not remove first element
Object firstElement = dequeA.getFirst(); //retrieves the first element of the queue
Object lastElement = dequeA.getLast(); //retrieves the lastelement of the queue
Object firstElement = dequeA.remove(); //to remove an element for a deque
Object firstElement = dequeA.removeFirst(); //remove the first element
Object lastElement = dequeA.removeLast(); //removes the lastelement
Object firstElement = dequeA.remove();
Object firstElement = dequeA.removeFirst();
Object lastElement = dequeA.removeLast();
The generic deque is used to make sure which type of objects get inserted into deque.
Deque deque = new LinkedList ();
This Deque can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them.
Here is how it looks:
My Object my Object = deque.remove();
for(MyObject anObject : deque){
//do someting to anObject...
}
A blocking deque supports blocking operations.
It is a Deque with operations that wait for the deque to become non- empty when retrieving an element.
Additionally, it waits for space to become available in the deque when storing an element.
It extends both the Deque and BlockingQueue interfaces (This interface is part of java.util.concurrent).
It is also thread Safe.
It does not allow null elements in.
It may or may not be capacity-constrained.
A BlockingDeque implementation may be used directly as a FIFO BlockingQueue.
It refers to a navigable set within the collections framework.
It is a SortedSet extended with navigation methods reporting closest matches for given search targets.
A NavigableSet may be accessed and traversed in either ascending or descending order depending on the requirement.
This interface is intended to supersede the SortedSet interface.
Collection , Iterable , Set , Sorted Set
It knows all Implementing Classes : ConcurrentSkipListSet, TreeSet.
It is a subtype of the SortedMap interface and makes navigation methods more convenient. It also has an added feature to make a submap from an existing map.
A Navigable map is a SortedMap extended with navigation methods which returns the closest matches for given search targets.
A NavigableMap may be accessed and traversed in either ascending or descending key order.
This interface is intended to supersede the SortedMap interface.
Interface NavigableMap< K,V >: K is the type of key maintained by this map and V is the type of mapped values
It knows all Superinterfaces : Map< K,V > , SortedMap< K,V >.
It knows all SubInterfaces : ConcurrentNavigableMap< K,V >
It knows all known Implementing Classes: ConcurrentSkipListMap, TreeMap
The ConcurrentNavigableMap provides support for concurrent access for the submaps. (This interface is a part of java.util.concurrent).
The ConcurrentMap is also a NavigableMap.
It knows all Superinterfaces:
ConcurrentMap< K,V >,Map< K,V >, NavigableMap< K,V >, SortedMap< K,V >
The following concrete implementation classes have been added:
ArrayDeque, also known as Array Double Ended Queue or Array Deck, is an efficient resizable-array implementation of the Deque interface.
Concurrent Skip List Set - concurrent scalable skip list implementation of the Navigable Set interface.
Concurrent Skip List Map - concurrent scalable skip list implementation of the ConcurrentNavigableMap interface.
Linked Blocking Deque - concurrent scalable optionally bounded FIFO blocking deque backed by linked nodes.
Abstract Map. Simple Entry - simple mutable implementation of Map.Entry.
Abstract Map.SimpleImmutable Entry - simple immutable implementation of Map.Entry.
These existing classes have been updated to implement new interfaces:
Two new methods were added to the Collections utility class:
There is no IdentityHashSet class, instead, you may use
Set< Object > identityHashSet= Collections.newSetFromMap(new IdentityHashMap< Object, Boolean>());
// before:
int[] newArray = new int[newLength];
System.arraycopy(oldArray,0, newArray,0,oldArray.length);
// After:
int[] newArray = Arrays.copyOf(a, newLength);
Deque is the abbreviation of "Double Ended Queue". It is a collection that allows us to add (or) remove elements at both ends. Deque supports the total size of collection for both fixed and unspecified size limits.
Deque implementation can be used as Stack (Last In First Out) or Queue (First In First Out). For each insertion, retrieval and removal of elements from deque, there are two different methods. One will throw exception if it fails in an operation and the other returns the status or special value for each operation.
Operation | Special value method | Exception throwing method |
---|---|---|
|
|
|
Implementation of Deque doesn't require preventing the insertion of null, but when we are using special value method, null is returned to indicate that the collection is empty. So, it is recommendable to not allow insertion of null.
ArrayDeque is a class that implements Deque. It has no capacity restrictions. It will perform faster than stack when used as stackand faster than linked list when used as queue. ArrayDeque is not thread safe.
The following example explains how to write program using ArrayDeque:
package com.javabykiran;
import java.util.ArrayDeque;
import java.util.Iterator;
public class ArrayDequeLab1 {
public static void main(String[] args){
ArrayDeque< String> ad = new ArrayDeque< String>();
//Insertion by using various methods
ad.add("by");
ad.addFirst("java");
ad.addLast("kiran");
System.out.println(ad);
//Retrievals
System.out.println("Retrieving First Element:"+ad.peekFirst());
System.out.println("Retrieving Last Element :"+ad.peekLast());
//Reverse traversal
System.out.println("Reverse traversal");
Iterator< String> itr = ad.descendingIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
//Removals
System.out.println("Removing First Element:"+ ad.pollFirst());
System.out.println("Removing Last Element :"+ ad.pollLast());
}
}
Output:
[java, by, kiran]
Retrieving First Element :java
Retrieving Last Element :kiran
Reverse traversal
Kiran
By
Java
Removing First Element :java
Removing Last Element :kiran
A blocking deque is basically a deque that waits for a deque to be non-empty while it retrieves an element. It will also wait for an empty space in the deque before storing an element.
A BlockingDeque is similar to Deque and provides additional functionality. When we try to insert an element in a BlockingDeque which is already full, it can wait till the space becomes available to insert an element. We can also specify the time limit for waiting.
Operation | Special Value | Throws Exception | Block | Times Out |
---|---|---|---|---|
Insertion Head | Add First(e) | Offer First(e) | Put First(e) | Offer First(e, time, unit) |
Removal from head | Remove first() | Poll First() | Take First() | Take First(Time, Unit) |
Retrieval from head | Get First() | Peak First() | NA | NA |
Insertion at tail | Add Last(e) | Offer Last(e) | Put Last(e) | Offer Last(e, Time, Unit) |
Removal from tail | RemoveLast() | Poll Last() | Take Last() | Take First (Time, Unit) |
Retrieval from tail | Get Last() | Peak Last() | NA | NA |
A LinkedBlockingDeque is a Collection class, which implements BlockingDeque interface in which we can specify maximum capacity if we want. If we did not specify the capacitythen the maximum capacity will be Integer.MAX_VALUE by default.
Example:
package com.javabykiran;
import java.util.concurrent.*;
class LinkedBlockingDequeLab implements Runnable {
LinkedBlockingDeque lbd= new LinkedBlockingDeque(1);
volatile boolean b = true;
public void run() {
try {
/*First thread once enters into the block it modifies
instance variable b to false and prevents second thread
to enter into the block
*/
if(b){
b = false;
Thread.sleep(5000); //Makes the Thread to sleep for 5
// seconds
System.out.println("Removing "+lbd.peek());
lbd.poll();//Removing an element from collection
}
else {
System.out.println("Waiting ");
/*This method makes to wait till the first thread removes // an elements*/
lbd.put('B');
System.out.println("Inserted "+lbd.peek());
}
} catch (Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
LinkedBlockingDequeLab bdeObj = new LinkedBlockingDequeLab();
bdeObj.lbd.offer('A');
System.out.println("Inserted"+bdeObj.lbd.peek());
Thread tMainObj = new Thread(bdeObj);
tMainObj.start();
Thread tSubObj = new Thread(bdeObj);
tSubObj.start();
}
}
Output:
Inserted A
Waiting
Removing A
Inserted B
“A navigable set is a sorted set that lets you work with its subsets in a variety of ways.” Suppose we have a requirement to:
Retrieve the element which is immediately greater than or lower than 15 from the given set: [5,10,15,20]
Retrieve all elements greater than or lower than 10.
With the help of existing methods we need to take few risks to achieve them. But with NavigableSet methods it becomes just a method call.
The NavigableSet method is used to return the closest matches of elements for the given elements in the collection.
The ConcurrentSkipListSet is one of the classes that implements NavigableSet.
Navigable set has the following interfaces: Collection< E >, Iterable< E >, Set< E >, SortedSet< E >, All Known implementing classes ConcurrentSkipListSet, TreeSet
What are the salient features of NavigableMap and ConcurrentSkipListMap and how do they differ?
NaviagableMap is similar to NaviagableSet
ConcurrentNavigableMap< K,V >
In NavigableSet, methods are used to return values, but in NaviagableMap, methods used to return the key, value pair.
ConcurrentSkipListMap is the one of the classes which implements NaviagableMap.
It knows all Superinterfaces Map< K,V >, SortedMap< K,V >
It knows all known implementing Classes ConcurrentSkipListMap, TreeMap.