Monday, April 18, 2011

JABBIR BASHA COLLECTIONS JAVA


Introduction to Collections Framework

Collections Framework:
The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating the groups of data into a single unit. The collections framework is a unified architecture which is used to represent and manipulate collections. The framework allows the collections to get manipulated independently, additionally it reduces the programming efforts and increases performance.

It includes implementation of interfaces and algorithms. Basically it is a unified architecture that consists the following collections:  

  1. Interfaces: These are the abstract data types that represent collections. With the help of interfaces we  manipulate collections independently. A hierarchy is generally formed with interfaces in object-oriented languages.
  2. Implementations: They are the reusable data structures with the concrete implementations of the collection interfaces.
  3. Algorithms: Algorithms are used to perform computations, such as searching, sorting etc on the objects that implement collection interfaces. They provide reusable functionality i.e. the same method can be used with different implementations of the collection interfaces. Hence they are also said to be polymorphic.  
  4. General-purpose Implementations: These are the primary implementations of the collection interfaces.  
  5. Infrastructure: Interfaces that provide essential support for the collection interfaces.  
  6. Array Utilities: Utility functions for arrays of primitives and reference objects.
    This functionality was added to the Java platform as a part of the Collections Framework. 
Advantages of collections framework:
The Java Collections Framework provides the following benefits:
  1. Reduces the efforts to learn and use the new APIs: We need not to learn multiple ad hoc collection APIs.  
  2. Fosters software reuse: It provides a standard interface for collections that fosters software reuse and also provides algorithms to manipulate them.  
  3. Reduces the efforts to design new APIs: It reduces the efforts required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.  
  4. Reduces the programming efforts: It provides useful data structures and algorithms that reduces programming efforts due to which we need not to write them ourselves.  
  5. Increases performance: It provides high-performance implementations of useful data structures and algorithms that increases the performance.
  6. Provides interoperability between the unrelated APIs: It helps in establishing a common language to pass collections back and forth to provide interoperability between the unrelated APIs.
  7. Provides resizable capability: Collection is resizable i.e.  it can grow dynamically.
Disadvantages of collections framework:
  1. It must cast to correct type.
  2. avoids the compile-time type checking.

Collection Interfaces:

The Collections Framework is made up of a set of interfaces  for storing and manipulating groups of data into a single unit. It consists of several interfaces, and classes that implement those interfaces, contained within the java.util package. It provides tools for maintaining a data container of objects. 

Different interfaces describe different types of functionalities.

The following diagrams shows the framework of core collection interfaces hierarchy.

Table of the ordered and unordered Collection interfaces shown as: 
 Interface name Ordered Allows duplicates Maps key to object
 Collection No Yes No
 Set No No No
 List Yes Yes No
 Map No No Yes
 SortedSet Yes No No
 SortedMap Yes No Yes
Collection Interface:
The Collection interface is the root interface for the Java collections hierarchy. It is extended by theListSet, and the SortedSet interfaces. The Collection interface is used to represent a group of objects, or elements. Typically, it represents data items that form a natural group. Some collection allows duplicate elements while others do not. It consists of both ordered and unordered elements.

 The declaration of the Collection interface is shown as:

public interface Collection<E>.. 
The <E> syntax tells that, the declared interface is a generic interface i.e. when you declare a Collection instance you should specify the type of object contained in the collection.
This interface supports basic operations like adding and removing. When you try to remove an element, only a single instance of the element in the collection is removed, if it is available. 

Following methods can be used for adding and deleting an element respectively.
boolean add(Object element)      
boolean remove(Object element)

The list of other methods belonging to the Collection interface is shown in the table given below
Method
Uses
 add(E o)
    
  Adds the specified element to this set if it is not already present (optional operation).
         
 clear()  Removes all of the elements from this set (optional operation).
contains(Object o) Returns true if this set contains the specified element.
 equals(Object o)  Compares the specified object with this set for equality.
 hashCode()  Returns the hash code value for this set.
  isEmpty()   Returns true if this set contains no elements.
 iterator()  Returns an iterator over the elements in this set.
 remove(Object o)  Removes the specified element from this set if it is present (optional operation).
 size()  Returns the number of elements in this set (its cardinality).

Set Interface:

The Set interface extends the Collectioninterface. It neither contains duplicate elements nor  maps a key value to an object. It permits a single element to benull. The Set interface contains only methods inherited from Collection interface, these are shown in the table given below:




Method
Uses
 add( )
Adds an object to the collection
 clear( )
Removes all objects from the collection
 contains( )
Returns true if a specified object is an element within the collection
 isEmpty( )
Returns true if the collection has no elements
 iterator( )
Returns an Iterator object for the collection which may be used to retrieve an object
 remove( )
Removes a specified object from the collection
 size( )
Returns the number of elements in the collection
In the Java platform, Collections Framework provides three general-purpose Set implementation-classes: 
 HashSet
 TreeSet
 LinkedHashSet

HashSet:
This is a class which stores its elements in a hash table and doesn't allow to store duplicate collections. This class permits the null element and is used to perform the basic operations such as add, remove, contains and size. This is the best way to perform set implementation.

TreeSet:
The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. The elements added to a TreeSet are sortable in an order. It is generally faster to add elements to a HashSet, then converting the collection to a TreeSet for sorted traversal.

 LinkedHashSet:
It is a class which is implements both the Hash table and linked list implementation of the Set interface. This implementation differs from HashSet that it maintains a doubly-linked list. The orders of its elements are based on the order in which they were inserted into the set (insertion-order). 

SortedSet Interface:
The SortedSet interface extends the Set interface. It maintains its elements in ascending order.  It neither contains duplicate elements nor  maps a key value to an object. It permits a single element to be null. In addition to methods of  the Set interface, it also provides two following methods:
 first( )
 last( ) 

The first( ) method returns the first (lowest) element currently in the collection while the last( ) method returns the last (highest) element currently in the collection.
Let see an example that stores a group of numbers to the Hash table using HashSet class.
import java.util.*;

public class SetDemo {
  public static void main(String args[]) { 
    int count[]={3422,10,60,30,22};
   Set<Integer> set = new HashSet<Integer>();
  try{
  for(int i=0; i<5; i++){
    set.add(count[i]);
  }
    System.out.println(set);
  
    TreeSet sortedSet=new TreeSet<Integer>(set);
  System.out.println("The sorted list is:");
    System.out.println(sortedSet);

    System.out.println(
"The First element of the set is: "+
                          (Integer)sortedSet.first());
    System.out.println(
"The last element of the set is: "+
                        (Integer)sortedSet.last());

  }
  catch(Exception e){}
  }
}

Output of the Program:

C:\nisha>javac SetDemo.java

C:\nisha>java SetDemo
[34, 22, 10, 30, 60]
The sorted list is:
[10, 22, 30, 34, 60]
The First element of the set is: 10
The last element of the set is: 60

C:\nisha>
This program creates a HashSet and adds a group of numbers, including a number "22" twice. The program than prints out the list of numbers in the set, note that the duplicate number is not added to the set. Then the program treats the set as a TreeSet and displays the sorted list of the set. The first( ) and the last( ) methods display the first & last elements of the set respectively.
         

Introduction to List and Queue Interface:

List Interface :
The List interface extends the Collectioninterface to define an ordered collection. It is also known as the sequence collection which permits duplicates element to accommodate in  the set but does not map a key value to an object. It permits one or more elements to be null. 
This interface adds position-oriented operations such as insert an element, getan element as well as remove or changean element based on their numerical position in the list. It also performs search operation to allow searching a specified object in the list and returns its numerical position.
In addition to methods of  the Set interface, it provides following three methods shown in the table below:
Method
Uses
 get( )
Returns the element at the specified index position in this collection
 listIterator( )
Returns a List Iterator object for the collection which may then be used to retrieve an object
 remove( )
Removes the element at the specified index position in this collection
Queue Interface:
Queue interface extends the Collection interface to define an ordered collection for holding elements  in a FIFO (first-in-first-out) manner to process them i.e. in a FIFO queue the element that is inserted firstly will also get removed  first. 
Besides basic collection operations, queues also provide additional operations such as insertion,removal, and inspection .
The Methods of this interface are as follows.

Method
Uses
 peek( )
Returns an element but if queue is empty then it returns null
 poll( )
Removes an element but returns null if the queue is empty.
In the Java platform, Collections Framework provides three general-purpose List and Queueimplementation-classes:
ArrayList
LinkedList
RunArrayList

The following program demonstrates the implementation of List and Queue interfaces.
import java.util.*;

public class ListQueueDemo {
  public static void main(String args[]) { 
    int numbers[]={3422,10,60,30};
   List <Integer>list = new ArrayList<Integer>();
  try{
  for(int i=0; i<5; i++){
    list.add(numbers[i]);
  }
  System.out.println("the List is: ");
    System.out.println(list);
  LinkedList <Integer>queue = new LinkedList<Integer>();
  for(int i=0; i<5; i++){
    queue.addFirst(numbers[i]);
  }
  System.out.println("The Oueue is: ");
     System.out.println(queue);
  queue.removeLast();
    System.out.println("After removing last element the queue is: "+ queue);
    
  }
  catch(Exception e){}
  }
}

Output of the Program:

C:\nisha>javac ListQueueDemo.java

C:\nisha>java ListQueueDemo
the List is:
[34, 22, 10, 60, 30]
The Oueue is:
[30, 60, 10, 22, 34]
After removing last element the queue is:
[30, 60, 10, 22]

C:\nisha>
This program creates a List and Queue, and inserts a group of numbers in these lists. The program than prints out the list of numbers in the set. The addFirst( ) and removeLast( ) methods add and remove an element in a FIFO manner, i.e. the first element of the queue is removed first 

Introduction to Map and SortedMap Interface:

Map Interface:
Map is an object that maps keys to values. It is not an extension of thecollection interface rather it has own interface hierarchy. Map provides a more general way for storing elementswithout containing duplicate keys. It allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Thus the keys in a map must be unique.
The Map interface methods can be broken down into three sets of operations:
Altering: The alteration operations allow you to add and remove key-value pairs from the map. Both the key and value can be null.
Querying: The query operations allow the user to retrieve key/value pairs from the Map.
Providing alternative views: This method allow you to work with the different views which can be used to analyze Map key/value Objects.

Map Methods Returning Views:
These methods return objects which allow you to traverse the elements of the Map, and also delete elements from the Map.
Method
Uses
 entrySet()
Returns a Set view of the mappings contained in the map. Each element in the set is a Map.Entry object which can have it's key and value elements accessed with getKey() and getValue() methods (also has a setValue() method)
keySet()Returns a Set view of the keys contained in the map. Removing elements from the Set will also remove the corresponding mapping (key and value) from the Map
values()Returns a Collection view of the values contained in the map. Removing elements from the Collection will also remove the corresponding mapping (key and value) from the Map
Map.Entry Interface:

Each element is a map has a key and value. Each key-value pair is saved in a java.util.Map.Entryobject. A set of these map entries can be obtained by calling a map's entrySet( ) method. Iterating over a map is done by iterating over this set.

The Collections Framework provides three general-purpose Map implementation:
HashMap
TreeMap
LinkedHashMap

HashMap:
The HashMap is a class which is used to perform some basic operations such as insertingdeleting, and locating elements in a Map . The  java.util.HashMap class is implemented with and roughly equivalent to a Hashtable  except that it is unsynchronized and permits null. It works with the Iteratorsrequires a well-defined implementation of the method hashCode( ).

TreeMap:
The TreeMap implementation is useful when you need to traverse the keys from a collection in a sorted manner. The elements added to a TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to add elements to a HashMap , then convert the map to a TreeMap for traversing the sorted keys.

LinkedHashMap:
A LinkedHashMap is implemented using both Hash table and linked list implementation of the Mapinterface. This implementation differs from HashMap that maintains a doubly-linked list running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order). 

The list of methods supported by Map interface are shown in the table given below:
Method
Uses
 put(Object key, Object value)
Associates the specified value with the specified key in the map.
 clear( )
Removes all mappings from the map
 putAll(Map t)
Copies all of the mappings from the specified map to the map.
 isEmpty( )
Returns true if this map contains no key-value mappings.
 iterator( )
Returns an Iterator object for the collection which may be used to retrieve an object.
 remove(Object key)
Removes the mapping for this key from this map if it is present.
 keySet( ) Returns a set view of the keys contained in this map.
 entrySet( ) Returns a set view of the mappings contained in this map.
 values( ) Returns a collection view of the values contained in this map.
 size( )
Returns the number of key-value mappings in this map.
SortedMap Interface:
The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap The SortedMap interface extends the Map interface which maintains its elements in ascending order. Working with a SortedMap is just similar to aSortedSet except, the sort is done on the map keys. In addition to methods of  the Map interface, it provides two methods shown as:
firstKey( )
lastKey( ) 

The firstKey( ) method returns the first (lowest) value currently in the map while the lastKey( ) method returns the last (highest) value currently in the map.
Let see an example implementing the HashMap and TreeMap class.
import java.util.*;

public class MapDemo {
  public static void main(String args[]) { 
    String days[]={"Sunday""Monday""Tuesday""Wednesnday",
                         
"Thursday""Friday""Saturday"};
   Map<Integer, String> map = new HashMap<Integer, String>();
  try{
  for(int i=0; i<7; i++){
    map.put(i, days[i]);
  }
  
  TreeMap<Integer, String> tMap=new TreeMap<Integer, String>(map);
     //Rerieving all keys
    System.out.println("Keys of tree map: " + tMap.keySet());
    //Rerieving all values
    System.out.println("Values of tree map: " + tMap.values());
    //Rerieving the First key and its value
    System.out.println("First key: " + tMap.firstKey() 
                  " Value: " 
+ tMap.get(tMap.firstKey()) "\n");
      
    //Removing the first key and value
    System.out.println("Removing first data: " 
                          + tMap.remove
(tMap.firstKey()));
    System.out.println("Now the tree map Keys: " + tMap.keySet());
    System.out.println("Now the tree map contain: " + tMap.values() "\n");
    //Rerieving the Last key and value
    System.out.println("Last key: " + tMap.lastKey() +
                       
" Value: " + tMap.get(tMap.lastKey()) "\n");  
    //Removing the last key and value
    System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
    System.out.println("Now the tree map Keys: " + tMap.keySet());
    System.out.println("Now the tree map contain: " + tMap.values());
  }
  catch(Exception e){}
  }
}

Output of this program:

C:\nisha>javac MapDemo.java

C:\nisha>java MapDemo
Keys of tree map: [0, 1, 2, 3, 4, 5, 6]
Values of tree map: [Sunday, Monday, Tuesday, Wednesnday, Thursday, Friday, Saturday]
First key: 0 Value: Sunday

Removing first data: Sunday
Now the tree map Keys: [1, 2, 3, 4, 5, 6]
Now the tree map contain: [Monday, Tuesday, Wednesnday, Thursday, Friday, Saturday]

Last key: 6 Value: Saturday

Removing last data: Saturday
Now the tree map Keys: [1, 2, 3, 4, 5]
Now the tree map contain: [Monday, Tuesday, Wednesnday, Thursday, Friday]

C:\nisha>
The given program stores the values mapping with their keys to the map. The keySet( ) method retrieves all keys from the map and the values( ) method retrieves all the values added to a map. The remove( )method removes the key from the map with its value specified in it.

Introduction to collection Implementations

The Collections Framework provides a well-designed set of interfaces and classes used for storing and manipulating groups of data into a single unit. The collections framework is a unified architecture which is used to represent and manipulate collections. The framework allows the collections to get manipulated independently as well as reduces programming effort for increasing performance. 
It includes implementations of interfaces, and algorithms included in it to manipulate them. Basically it is a unified architecture that consists the following collections:  

Implementations are the reusable data objects used to store collections, which implement the collection interfaces.  Implementations are also responsible for documenting the operations which they support. All of the general-purpose implementations of the Java platform support all of the optional operations.
The following kinds of implementations are described below:
  • General-purpose implementations: These are the most commonly used implementations, designed for performing all optional operations contained within the defined interfaces. They are summarized in the table below.
InterfacesImplementations
 Hash tableTreeLinked listHash table + Linked list
SetHashSetTreeSet LinkedHashSet
List  LinkedList 
Queue    
MapHashMapTreeMap LinkedHashMap

  • The Java Collections Framework provides several general-purpose implementations of the Set,List , and Map interfaces. Each of the general-purpose implementations provides all optional operations contained in its interface. All permit null elements, keys, and values.
  • Special-purpose implementations: These are designed to use in special situations and display nonstandard performance characteristics, usage restrictions, or behavior.
  • Concurrent implementations: These are designed to support high concurrency. These implementations are part of the java.util.concurrent package.
  • Wrapper implementations: These are used in combination with other types of implementations.
  • Convenience implementations: These are mini-implementations, typically made via static factory methods, that provide convenient, efficient alternatives to general-purpose implementations for special collections.
  • Abstract implementations: These are implementations that facilitate the construction of custom implementations.
The following description describes the categories in which the Collection Framework interfaces are implemented.
The Set implementations are grouped into general-purpose and special-purpose implementations. Listimplementations are grouped into general-purpose and special-purpose implementations. Mapimplementations are grouped into general-purpose, special-purpose, and concurrent implementations. The Queue implementations are grouped into general-purpose and concurrent implementations.

Introduction to Collection Algorithms

Algorithms:
The Collections and Arrays classes, available as a part of the Collections Framework, support various algorithms. The  Java platform provides great majority of the algorithms to perform different kind of operations such as sorting andsearching.
I. Sorting Algorithm:
The sort algorithm reorders a List such that its elements are in ascending order according to an ordering relationship. Thesort operation uses a slightly optimizedmerge sort algorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted version of sets and maps, there is no sorted Listcollection implementation. Sorting of a List is done with the sort( ) method.
For example, the following program prints the arguments (the arguments, given through command line) of a  List in an alphabetical order.
import java.util.*;

public class SortDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList(args);
        Collections.sort(list);
        System.out.println(list);
    }
}
 Output of this program:
C:\nisha>java SortDemo this is a commandline argument
[a, argument, commandline, is, this]

C:\nisha>
Searching Algorithm :
Besides sorting, the Collections and Arrays classes provide a mechanism to search a List or an array, as well as to find the first and last values within a Collection. The binarySearch algorithm searches for a specified element in a sorted List. This algorithm  takes a List and an element to search for thesearch key. This form assumes that the List is sorted in ascending order according to the natural ordering of its elements.
Before searching an element, the List must be sorted, Once you have sorted the List, usingCollection.sort( ) method, you can perform a quickly binary search  operation using the overriddenbinarySearch( ) method. 
For example, the following program prints the sorted arguments list (the arguments, given through command line) and then search the position of a specified key value.
import java.util.*;

public class SearchDemo {
    public static void main(String[] args) {
    try{
        List<String> list = Arrays.asList(args);
        Collections.sort(list);
        System.out.println("The sorted list is: "+list);
    int pos = Collections.binarySearch(list, list.get(2));
    System.out.println("The position of the searched element is : "+pos
                     +
" and the element is:"+list.get(2));
    }
    catch(Exception e){}
           
    }
}
 Output of this program:
C:\nisha>java SearchDemo this is a commandline argument
The sorted list is: [a, argument, commandline, is, this]
The position of the searched element is : 2 and the element is:commandline

C:\nisha>

Custom Collection Implementations

So far you have learnt about the Java  built-in Collection Interfaces implementations. Apart from these, some times programmer need to implement their own collections classes.  The Java platform allows you to write your own implementation of a core collection interface. It is easy to write your own  implementation with the help of abstract implementations
Lets discuss, why we should make a custom implementation.
  • Persistent: All of the built-in Collection implementations reside in main memory and appears when the program exits. If you want a collection to be available for the next time when the program starts, you can implement a collection that is concurrently accessible by multiple programs.
  • High-performance, special-purpose: Many data structures take advantage of restricted usage to offer better performance that is possible with general-purpose implementations. For instance, consider a List containing long runs of identical element values. The runs can be represented as a single object containing the repeated element. This example is interesting because it deals with two aspects of performance: It requires less space but more time than an ArrayList.
  • High-performance, general-purpose: The Java Collections Framework's designers have tried to provide the best general-purpose implementations for each interface, but many, new ones are invented every day for the High performance of an application.
  • Convenience: Some times you want additional implementations that offers conveniences than those offered by the Java platform. For instance, you may need a List to represent a contiguous range of Integers.
To write your own custom implementation is not difficult. Java supports the abstract implementations to implement your own collection. Lets see the way of writing the custom collection implementation.
import java.util.*;

  class MyClass {
    public static List myList(Object[] a) {
       return new ArrayList(a);
    }
  }
    class ArrayList extends AbstractList
               implements java.io.Serializable {
    
  private Object[] x;

  ArrayList(Object[] array) {
      x = array;
  }
  public Object get(int index) {
      return x[index];
  }
  public Object set(int index, Object element) {
      Object oldVal = x[index];
      x[index= element;
      return oldVal;
  }
  public int size() {
      return x.length;
  }
    }
  public class CustomImpl{
   public static void main(String[] args) {
        try{
      String s[]={"My""Custom""Implementation"};
      Object o;
      int i=0;
      MyClass a= new MyClass();
      List lst=a.myList(s);
      System.out.println("The list is: "+lst);
      ArrayList al=new ArrayList(s);
      o=al.get(1);
      System.out.println("The retrieved element is: "+o);
      String s1="Collection";
      o=al.set(2,s1);
      System.out.println("The set element in place of Implementation is: "+s1);
      System.out.println("Now the new list is: "+lst);
      i=al.size();
      System.out.println("The size of the array list is: "+i);
      }
      catch(Exception e){}
    }
    }

Output of the Program:

C:\nisha>javac CustomImpl.java

C:\nisha>java CustomImpl
The list is: [My, Custom, Implementation]
The retrieved element is: Custom
The set element in place of Implementation is: Collection
Now the new list is: [My, Custom, Collection]
The size of the array list is: 3

C:\nisha>
Description of the Program:
In the given program, a custom implementation of Arrays.myList is defined which calls the constructor ofArrayList class and pass the object to it. The get( ) and the set( ) methods of the ArrayList class retrieve and set an element to the specified position of the List.

Java 6.0 Collection Framework:

Some of the new collections APIs have been introduced in Java 6.0. These are:
  1. Deque: It is used to represent Double ended queue. With the help of this collection we can add or remove elements at both the ends. Deque implementation can be used as Stack (Last in first out) or Queue (First in First Out). There are two methods in Deque, which are used for insertion, retrieval and removal of elements. One returns status or special value for each operation and the other will throw exception if it fails in an operation.
  1. BlockingDeque: It is similar to Deque but with added functionality. When we try to insert an element in a BlockingDeque and if the BlockingDeque is already full then the element can wait till the space becomes available to insert an element. There are four methods available for BlockingDeque.
    • Methods throws exception
    • Methods that times out (Waits for a given time for space to available)
    • Methods that blocks (Waits indefinitely for space to available)
    • Methods returns special value
  1. NavigableSet: It is used to return the closest matches of elements. For instance if we want retrieve the element, which is immediately greater than, or lower than element 20 or if we want to retrieve all elements greater than or lower than 35 from sorted set elements [10,20,35,5] we can use NavigableSet methods that becomes just a method call. ConcurrentSkipListSet is one of the class that implements NavigableSet.
  1. NavigableMap: In NavigableSet, methods use to return values, but in NaviagableMap methods used to return the key,value pair.ConcurrentSkipListMap is the one of the class which implements NaviagableMap
Some of the new Classes are: 
  1. ArrayDeque: ArrayDeque is a class that implements Deque. If used as a stack or linked list, it performs much faster than before. It is neither thread safe nor has capacity restrictions.
  1. LinkedBlockingDeque: It implements BlockingDeque. Maximum capacity can be specified by using BlockingDeque interface. However the maximum capacity will be Integer.MAX_VALUE if not specified.
  1. ConcurrentSkipListSet: ConcurrentSkipListSet is one of the class that implements NavigableSet. It is used to return the closest matches of elements.
  1. ConcurrentSkipListMap: ConcurrentSkipListMap is the one of the class which implements NaviagableMap. In NavigableSet, methods use to return values.
  1. AbstractMap.SimpleEntry: The key value pair of one single entry in a Map is held by the instance of this class. Moreover it is a static nested class nested insideabstractMap class. 
       
  2. AbstractMap.SimpleImmutableEntry: This class is similar to AbstractMap.SimpleEntryclass however it has one difference that it throws the exceptionUnsupportedOperationException when we try to set a value whileAbstractMap.SimpleEntry doesn’t.
Updated Classes in Java 6.0
  1.  LinkedList
     
  2. TreeSet
     
  3. TreeMap
     
  4. Collections
Modified classes                      
To implement the new interfaces we modify some classes like TreeSet is modified to implement NavigableSet, LinkedList is modified to implement Deque, TreeMap is modified to implement NavigableMap etc. Some of the new methods like newSetFromMap and asLifoQueue have been added to Collections 2.
 Hence the bi- directional traversal has become easier with java6.0 collections. We can even retrieve elements as desired.

Collections Framework Enhancements

In Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides some new Collection interfaces also.

Following new Interfaces and Classes are provided in JAVA SE 6 :

  • Deque – Deque is a interface. It is a short for “Double Ended Queue”. This interface defines some methods that access the element at both ends. That means by the methods of this interface we can add and remove the elements at both ends.
  • ArrayDeque – ArrayDeque Class implements a Deque interface. This class have no capacity restriction, it can grow according to usage. If the external Synchronization is not available then it don’t support concurrent access by multiple thread.
Constructors Details :
  • public ArrayDeque()
    Above Constructor is used to make a empty array deque with an default capacity that 16 elements.
  • public ArrayDeque(int numElements)
    Above Construtor is used to make a empty array deque with the initial capacity that is sufficient to hold the specified elements.
  • public ArrayDeque<Etype>()
    Etype is the type of the elements that held in this Collection. Above Constructor is used to make a array deque containing elements of specified type.
Methods Details :
  • void addFirst(Etype e)
    Above method is used to insert the element at the starting point of the array deque
  • void addLast(Etype e)
    Above method is used to insert the element at the end point of the array deque.
      Above two methods throws following Exception:
  1. IllegalStateException – Due to capacity restriction the element cannot be added.
  2. ClassCastException – Class of the specified element prevents it from being added to this deque
  3. NullPointerException – If specified element is null.
  4. IllegalArgumentException – If element having some property that prevent it from being added to this deque
  • boolean offerFirst(Etype e)
    Above method is also used to insert the specified element at the starting point of the array deque. This method is preferable when we using a capacity restricted deque. When element is added in array deque then its return true else it return false.
  • boolean offerLast(Etype e)
    Above method is also used to insert the specified element at the end point of the array deque. This method is preferable when we using a capacity restricted deque. When element is added in array deque then its return true else it return false.
    Above two methods throws following Exception: 
  1. ClassCastException – Class of the specified element prevents it from being added to this deque.
  2. NullPointerException – If specified element is null.
  3. IllegalArgumentException – If element having some property that prevent it from being added to this deque.
  • Etype removeFirst()
    Above method is used to remove the first element of the array deque. And we can also retrieve this element. But if array deque is empty then it throws a NoSuchElementException.
  • Etype removeLast()
    Above method is used to remove the last element of the array deque. And we can also retrieve this element. But if array deque is empty then it throws a NoSuchElementException.
  • Etype pollFirst()
    Above method is same as removeFirst(). It is also used to retrieve and remove the first element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype pollLast()
    Above method is same as removeLast(). It is also used to retrieve and remove the last element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype getFirst()
    Above method is used just for retrieving the first element of deque. But if array deque is empty then it throws a NoSuchElementException.
  • Etype getLast()
    Above method is used just for retrieving the last element of deque. But if array deque is empty then it throws a NoSuchElementException.
  • Etype peekFirst()
    Above method is same as getFirst().It is also used to retrieving the first element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype peekLast()
    Above method is same as getLast().It is also used to retrieving the last element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • boolean removeFirstOccurrence(Object obj)
    Above method is used to remove the first occurrence of the specified element. It return true when the specified element was remove. But if the deque does not contain the specified element it is unchanged.
  • boolean removeLastOccurrence(Object obj)
    Above method is used to remove the last occurrence of the specified element. It return true when the specified element was remove. But if the deque does not contain the specified element it is unchanged.
The following example demonstrates the above methods:
import java.io.*;
import java.util.*;
public class NewDeque
{
public static void main(String s[])throws IOException
 {
Console c=System.console();
  if(c==null)  
  {
   System.err.println("Console object is not available");
   System.exit(1);
  }
   ArrayDeque<String> dqname = new ArrayDeque<String>();
   String name = null;
name = c.readLine("Enter any String: ");
   dqname.add(name);    
   show(dqname);
 
   name=c.readLine("Enter any string to add on starting 
point of deque by addFirst():");
   dqname.addFirst(name);
   show(dqname);
name=c.readLine("Enter any string to add on ending 
point of deque by addLast():");
   dqname.addLast(name);
   show(dqname);
name=c.readLine("Enter any string to add on starting
 point of deque by offerfirst() :");
   dqname.offerFirst(name);
   show(dqname);
name=c.readLine("Enter any string to add on ending 
point of deque by offerlast() :");
   dqname.offerLast(name);
   show(dqname);
System.out.println("Getting the first element 
by using getFirst()");
   String str1=dqname.getFirst();
   System.out.println("First element is  : "+str1);
System.out.println("Getting the Last element by using 
getLast()");
   str1=dqname.getLast();
   System.out.println("Last element is  : "+str1);
 
System.out.println("Getting the first element by 
using peekFirst()");
   str1=dqname.peekFirst();
   System.out.println("First element is  : "+str1);
 
System.out.println("Getting the Last element by
 using peekLast()");
   str1=dqname.peekLast();
   System.out.println("Last element is  : "+str1);
System.out.println("Removing the first element
 by using removeFirst()");
   str1=dqname.removeFirst();
   show(dqname);   
System.out.println("Removing the Last element
 by using removeLast()");
   str1=dqname.removeLast();
show(dqname);
System.out.println("Removing the first element
 by using pollFirst()");
   str1=dqname.pollFirst();
   show(dqname);
System.out.println("Removing the Last element
 by using pollFirst()");
   str1=dqname.pollLast();
   show(dqname);
 }
static void show(ArrayDeque<String> dqname)
   {
   Iterator<String> nameIter = dqname.iterator();
    while(nameIter.hasNext())
System.out.println(nameIter.next()); 
   }
}
Output of the program is:  
C:\j2se6>javac NewDeque.java

C:\j2se6>java NewDeque
Enter any String: Rose
Rose
Enter any string to add on starting point of deque by addFirst():India
India
Rose
Enter any string to add on ending point of deque by addLast():Net
India
Rose
Net
Enter any string to add on starting point of deque by offerfirst() :Com
Com
India
Rose
Net
Enter any string to add on ending point of deque by offerlast() :Chandan
Com
India
Rose
Net
Chandan
Getting the first element by using getFirst()
First element is : Com
Getting the Last element by using getLast()
Last element is : Chandan
Getting the first element by using peekFirst()
First element is : Com
Getting the Last element by using peekLast()
Last element is : Chandan
Removing the first element by using removeFirst()
India
Rose
Net
Chandan
Removing the Last element by using removeLast()
India
Rose
Net
Removing the first element by using pollFirst()
Rose
Net
Removing the Last element by using pollFirst()
Rose

C:\j2se6>

Navigable Map Example

We already know that NavigableMap is similar to NavigableSet. In NavigableMap we use methods to return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to return values.ConcurrentSkipListMap is the one of the class which implements NavigableMap. Lets have a look at the example.
Description of program:
The following program helps you in inserting, removing and retrieving the data from the NavigableMap. It uses the put() method to add the element. If you want to retrieve the data at first and last position from the NavigableMap, you use the firstEntry() and lastEntry() methods. ThedescendingMap() method represents all data to the NavigableMap in descending order. 
You can retrieve the nearest less than or equal to the given number and the greatest key strictly less than the given number floorEntry() and lowerEntry() methods. And you retrieve a key-value associated with the least key strictly greater than the given key, you use the higherEntry() method. ThepollFirstEntry() method removes the first data from the NavigableMap and pollLastEntry() method also removes the data at the last position from the NavigableMap.
Here is the code of program:
import java.util.*;
import java.util.concurrent.*;

public class NavigableMapExample{
  public static void main(String[] args) {
    System.out.println("Navigable Map Example!\n");
    NavigableMap <Integer, String>navMap = new
                       
ConcurrentSkipListMap<Integer, String>();
    navMap.put(1"January");
    navMap.put(2"February");
    navMap.put(3"March");
    navMap.put(4"April");
    navMap.put(5"May");
    navMap.put(6"June");
    navMap.put(7"July");
    navMap.put(8"August");
    navMap.put(9"September");
    navMap.put(10"October");
    navMap.put(11"November");
    navMap.put(12"December");
    //Displaying all data
    System.out.println("Data in the navigable map: " +
                                          navMap.descendingMap
()+"\n");
    //Retrieving first data
    System.out.print("First data: " + navMap.firstEntry()+"\n");
    //Retrieving last data
    System.out.print("Last data: " + navMap.lastEntry()+"\n\n");
    //Retrieving the nreatest less than or equal to the given key
    System.out.print("Nearest less than or equal to the given key: "
                            
+ navMap.floorEntry(5)+"\n");
    //Retrieving the greatest key strictly less than the given key
    System.out.println("Retrieving the greatest key strictly less than
                         the given key: " 
+ navMap.lowerEntry(3));
    //Retrieving a key-value associated with the least key
                    strictly greater than the given key

    System.out.println("Retriving data from navigable map greter than
                 the given key: " 
+ navMap.higherEntry(5)+"\n");
    //Removing first
    System.out.println("Removing First: " + navMap.pollFirstEntry());
    //Removing last
    System.out.println("Removing Last: " + navMap.pollLastEntry()+"\n");
    //Displaying all data
    System.out.println("Now data: " + navMap.descendingMap());
  }
}
Output of program:
C:\vinod\collection>javac NavigableMapExample.java

C:\vinod\collection>java NavigableMapExample
Navigable Map Example!

Data in the navigable map: {12=December, 11=November, 10=October, 9=September, 8
=August, 7=July, 6=June, 5=May, 4=April, 3=March, 2=February, 1=January}

First data: 1=January
Last data: 12=December

Nearest less than or equal to the given key: 5=May
Retrieving the greatest key strictly less than the given key: 2=February
Retriving data from navigable map greter than the given key: 6=June

Removing First: 1=January
Removing Last: 12=December

Now data: {11=November, 10=October, 9=September, 8=August, 7=July, 6=June, 5=May
, 4=April, 3=March, 2=February}

C:\vinod\collection>

HashSet Example

In this section we are discussing HashSetwith example code that shows the methods to add, remove and iterate the values of collection. HashSet is a collection set that neither allows duplicate elements nor order or position its elements.
Description of program:
In the following code segment we are performing various operations on HashSetcollectionWe have explained the steps to add, remove, and test the elements of the collection. Keys are used to put and get values. We can also execute this code on a Vector by changing the HashSet declaration and constructor to a Vector as it supports the collection interface.  
To insert an element in the HashSet collection add() method is used. The size() method helps you in getting the size of the collection. If you want to delete any element, use the remove() method which takes index as parameter. In order to remove all data from the HashSet use clear() method. When the HashSet is empty, our program checks for it and displays a message "Collection is empty". If the collection is not empty then program displays the size of HashSet.
Here is the code of program:
import java.util.*;

public class CollectionTest {
  public static void main(String [] args) {   
    System.out.println"Collection Example!\n" )
    int size;
    // Create a collection      
    HashSet <String>collection = new HashSet <String>();
    String str1 = "Yellow", str2 = "White", str3 = "Green", str4 = "Blue";  
    Iterator iterator;
    //Adding data in the collection
    collection.add(str1);    
    collection.add(str2);   
    collection.add(str3);   
    collection.add(str4);
    System.out.print("Collection data: ");  
    //Create a iterator
    iterator = collection.iterator();     
    while (iterator.hasNext()){
      System.out.print(iterator.next() " ");  
    }
    System.out.println();
    // Get size of a collection
    size = collection.size();
    if (collection.isEmpty()){
      System.out.println("Collection is empty");
    }
    else{
      System.out.println"Collection size: " + size);
    }
    System.out.println();
    // Remove specific data      
    collection.remove(str2);
    System.out.println("After removing [" + str2 + "]\n");
    System.out.print("Now collection data: ");
    iterator = collection.iterator();     
    while (iterator.hasNext()){
      System.out.print(iterator.next() " ");  
    }
    System.out.println();
    size = collection.size();
    System.out.println("Collection size: " + size + "\n");
    //Collection empty
    collection.clear();
    size = collection.size();
    if (collection.isEmpty()){
      System.out.println("Collection is empty");
    }
    else{
      System.out.println"Collection size: " + size);
    }
  }
}
Output of this program:
C:\vinod\collection>javac CollectionTest.java

C:\vinod\collection>java CollectionTest
Collection Example!

Collection data: Blue White Green Yellow
Collection size: 4

After removing [White]

Now collection data: Blue Green Yellow
Collection size: 3

Collection is empty

C:\vinod\collection>

Linked List Example:








No comments:

Post a Comment