Friday, October 28, 2011

Collections



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.








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 the List, Set, 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 Collection interface. It neither contains duplicate elements nor  maps a key value to an object. It permits a single element to be null. 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 Collection interface 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, get an element as well as remove or change an 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:
A 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 Queue implementation-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
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
Map Interface:
A Map is an object that maps keys to values. It is not an extension of the collection interface rather it has own interface hierarchy. Map provides a more general way for storing elements without 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.Entry object. 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 inserting, deleting, 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 Iterators requires 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 Map interface. 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 a SortedSet 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 TreeMapclass.
import java.util.*;

public class MapDemo {
  public static void main(String args[]) {
    String days[]={"Sunday", "Monday", "Tuesday", "Wednesnday",
                         "Thursday", "Friday", "Saturday"};
   Map map = new HashMap();
  try{
  for(int i=0; i<7; i++){
    map.put(i, days[i]);
  }
 
  TreeMap tMap=new TreeMap(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
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
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.
Interfaces
Implementations

Hash table
Tree
Linked list
Hash table + Linked list
Set
HashSet
TreeSet

LinkedHashSet
List


LinkedList

Queue




Map
HashMap
TreeMap

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. List implementations are grouped into general-purpose and special-purpose implementations. Map implementations 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
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
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 and searching.
I. Sorting Algorithm:
The sort algorithm reorders a List such that its elements are in ascending order according to an ordering relationship. The sort operation uses a slightly optimized merge sort algorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted version of sets and maps, there is no sorted List collection 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 the search 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, using Collection.sort( ) method, you can perform a quickly binary search  operation using the overridden binarySearch( ) 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
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
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 of ArrayList 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
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
 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 inside abstractMap class.
     
  2. AbstractMap.SimpleImmutableEntry: This class is similar to AbstractMap.SimpleEntry class however it has one difference that it throws the exception UnsupportedOperationException when we try to set a value while AbstractMap.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>
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.
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. The descendingMap() 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. The pollFirstEntry() 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>
In the example below we have used NavigableSet method to sort the elements in ascending order, descending order, also to retrieve the element which is immediately greater than or equal to 35 etc.
Navigable Set Example
  
In the example below we have used NavigableSet method to sort the elements in ascending order, descending order, also to retrieve the element which is immediately greater than or equal to 35 etc. With the help of NavigableSet methods its just a method call to get the result. It is used to return the closest matches of elements for the given elements in the collection.  
Description of program:
Inserting the data in the NavigableSet by the add() method. The NavigableSet provides the facility to getting the data in both orders: ascending and descending orders. The descendingSet() method returns the data from the NavigableSet in descending order. If you want to get the data in ascending order must be used an iterator. An iterator stores the data as a index and the hasNext() method returns 'true' until, the next() method returns the element in ascending order. 
Here, you remove the element from the NavigableSet at first and last position, you use the pollFirst() and pollLast() methods. Sometimes, you want to get the less and greater than or equal to the given element by using the floor() and ceiling() methods. For getting the all elements of the NavigableSet that is greater than or equal to the given element by the tailSet() method and less than or equal to the given element of the NavigableSet by the headSet() method. 
Here is the code of program:
import java.util.*;
import java.util.concurrent.*;

public class NavigableSetExample{
  public static void main(String[] args) {
  System.out.println("Navigable set Example!\n");
  NavigableSet <Integer>nSet = new ConcurrentSkipListSet<Integer>();
  nSet.add(10);
  nSet.add(20);
  nSet.add(50);
  nSet.add(30);
  nSet.add(100);
  nSet.add(80);
  // Returns an iterator over the elements in navigable set,
    in ascending order.
  Iterator iterator = nSet.iterator();
  System.out.print("Ascending order navigable set: ");
  //Ascending order list
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");
  }
  System.out.println();
  //Descending order list
  System.out.println("Descending order navigable set: " 
   nSet.descendingSet() + "\n");
  //Greater than or equal to the given element
  System.out.println("Least element in Navigable set greater than 
   or equal to 35: " + nSet.ceiling(35));
  //Less than or equal to the given element
  System.out.println("Greatest element in Navigable set less than 
   or equal to 35: " + nSet.floor(35) + "\n");
  //Viewing the portion of navigable set whose elements are 
  strictly less than the given element
  System.out.println("Navigable set whose elements are strictly 
   less than '40': " + nSet.headSet(40));
  //Viewing the portion of navigable set whose elements are 
  greater than or equal to the given element
  System.out.println("Navigable set whose elements are greater 
  than or equal to '40': " + nSet.tailSet(40) + "\n");
  //Removing first element from navigable set
  System.out.println("Remove element: "+nSet.pollFirst());
  //After removing the first element, now get navigable set
  System.out.println("Now navigable set: " + nSet.descendingSet() + "\n");
  //Removing last element from navigable set
  System.out.println("Remove element: " + nSet.pollLast());
  //After removing the last element, now get navigable set
  System.out.println("Now navigable set: " + nSet.descendingSet());
  }
}
Output of this program
C:\vinod\collection>javac NavigableSetExample.java

C:\vinod\collection>java NavigableSetExample
Navigable set Example!

Ascending order navigable set: 10 20 30 50 80 100
Descending order navigable set: [100, 80, 50, 30, 20, 10]

Least element in Navigable set greater than or equal to 35: 50
Greatest element in Navigable set less than or equal to 35: 30

Navigable set whose elements are strictly less than '40': [10, 20, 30]
Navigable set whose elements are greater than or equal to '40': [50, 80, 100]

Remove element: 10
Now navigable set: [100, 80, 50, 30, 20]

Remove element: 100
Now navigable set: [80, 50, 30, 20]

C:\vinod\collection>
HashSet Example
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
In this section we are discussing HashSet with example code that shows the methods to add, remove and iterate the values of collection. A 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 HashSet collection. We 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

This section discusses an example to demonstrate the various methods of List interface. We are using two classes ArrayList and LinkedList in the example code. The code below is similar to the previous example, but it performs many List operations. Lets discuss the example code.
Description of program:
This program helps you in storing the large amount of data as a collection. The LinkedList is a part of collection that constructs a list containing the elements of the specified collection. Iterator methods returns the values in the order in which they are stored.
If you want to insert the data in the linkedList then use add() method. The hasNext() method returns true if the iterator contains more elements and the next() method returns the next element in the iteration. To insert and remove the data at first, last and specified position in the linkedList, you use the addFirst(), addLast(), add(), removeFirst(), removeLast() and remove() methods. To retrieve the element with respect to a specified position use the getFirst(), getLast() and get() methods.  
Here is the code of program:
import java.util.*;

public class LinkedListExample{
  public static void main(String[] args) {
  System.out.println("Linked List Example!");
  LinkedList <Integer>list = new LinkedList<Integer>();
  int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
  int size;
  Iterator iterator;
  //Adding data in the list
  list.add(num1);
  list.add(num2);
  list.add(num3);
  list.add(num4);
  size = list.size();
  System.out.print( "Linked list data: ");  
  //Create a iterator
  iterator = list.iterator(); 
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  //Check list empty or not
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  System.out.println("Adding data at 1st location: 55");
  //Adding first
  list.addFirst(55);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at last location: 66");
  //Adding last or append
  list.addLast(66);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  System.out.println("Adding data at 3rd location: 55");
  //Adding data at 3rd position
  list.add(2,99);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Retrieve first data
  System.out.println("First data: " + list.getFirst());
  //Retrieve lst data
  System.out.println("Last data: " + list.getLast());
  //Retrieve specific data
  System.out.println("Data at 4th position: " + list.get(3));
  //Remove first
  int first = list.removeFirst();
  System.out.println("Data removed from 1st location: " + first);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove last
  int last = list.removeLast();
  System.out.println("Data removed from last location: " + last);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove 2nd data
  int second = list.remove(1);
  System.out.println("Data removed from 2nd location: " + second);
  System.out.print("Now the list contain: ");
  iterator = list.iterator();
  //After removing data
  while (iterator.hasNext()){
  System.out.print(iterator.next()+" ");  
  }
  System.out.println();
  System.out.println("Now the size of list: " + list.size());
  //Remove all
  list.clear();
  if (list.isEmpty()){
  System.out.println("Linked list is empty");
  }
  else{
  System.out.println( "Linked list size: " + size);
  }
  }
}
Output of program:
C:\vinod\collection>javac LinkedListExample.java

C:\vinod\collection>java LinkedListExample
Linked List Example!
Linked list data: 11 22 33 44
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22 33 44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22 33 44 66
Now the size of list: 6
Adding data at 3rd location: 55
Now the list contain: 55 11 99 22 33 44 66
Now the size of list: 7
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location: 55
Now the list contain: 11 99 22 33 44 66
Now the size of list: 6
Data removed from last location: 66
Now the list contain: 11 99 22 33 44
Now the size of list: 5
Data removed from 2nd location: 99
Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty

C:\vinod\collection>
Tree Map Example
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
In the following example, we have used the TreeMap method, which stores its elements in a tree and orders its elements based on their values. Here in the example we have used the key of the element to show the values of the element. To retrieve the keys and values use keySet() and values() method respectively. 
This program shows the data elements left after removing the particular element by specifying its key. Using the Iterator interface methods, we can traverse a collection from start to finish and safely remove elements from the underlying Collection.
 Here is the code of program:
import java.util.*;

public class TreeMapExample{
public static void main(String[] args) {
System.out.println("Tree Map Example!\n");
TreeMap <Integer, String>tMap = new TreeMap<Integer, String>();
//Addding data to a tree map
tMap.put(1, "Sunday");
tMap.put(2, "Monday");
tMap.put(3, "Tuesday");
tMap.put(4, "Wednesday");
tMap.put(5, "Thursday");
tMap.put(6, "Friday");
tMap.put(7, "Saturday");
//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 value from key with key number 5
System.out.println("Key: 5 value: " + tMap.get(5)+ "\n");
//Rerieving the First key and its value
System.out.println("First key: " + tMap.firstKey() + " Value: "
+ tMap.get(tMap.firstKey()) + "\n");
//Rerieving the Last key and value
System.out.println("Last key: " + tMap.lastKey() + " Value: "
+ tMap.get(tMap.lastKey()) + "\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");
//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());
}
}
Output of this program:
C:\vinod\collection>javac TreeMapExample.java

C:\vinod\collection>java TreeMapExample
Tree Map Example!

Keys of tree map: [1, 2, 3, 4, 5, 6, 7]
Values of tree map: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
Key: 5 value: Thursday

First key: 1 Value: Sunday

Last key: 7 Value: Saturday

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

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

C:\vinod\collection>

Tree Set Example

http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
In the following example, we have used the TreeSet collection, which is similar to TreeMap that stores its elements in a tree and maintain order of its elements based on their values. To get the size of TreeSet collection size() method is used. Our TreeSet collection contains 4 elements and the size of the TreeSet can be determine by calling size() method. 
Similarly, we have used first() and last() to retrieve first and last element present in the TreeSet. Program also shows the method to remove the element and then display the remaining elements. To remove all data from the TreeSet, use the clear() method. To determine whether TreeSet is empty or not use isEmpty() method. If the TreeSet is empty, it displays the message "Tree set is empty." otherwise it displays the size of TreeSet.
 Here is the code of program:
import java.util.*;

public class TreeSetExample{
  public static void main(String[] args) {
  System.out.println("Tree Set Example!\n");
  TreeSet <Integer>tree = new TreeSet<Integer>();
  tree.add(12);
  tree.add(23);
  tree.add(34);
  tree.add(45);
  Iterator iterator;
  iterator = tree.iterator();
  System.out.print("Tree set data: ");
  //Displaying the Tree set data
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");
  }
  System.out.println();
  //Check impty or not
  if (tree.isEmpty()){
  System.out.print("Tree Set is empty.");
  }
  else{
  System.out.println("Tree Set size: " + tree.size());
  }
  //Retrieve first data from tree set
  System.out.println("First data: " + tree.first());
  //Retrieve last data from tree set
  System.out.println("Last data: " + tree.last());
  if (tree.remove(30)){
  System.out.println("Data is removed from tree set");
  }
  else{
  System.out.println("Data doesn't exist!");
  }
  System.out.print("Now the tree set contain: ");
  iterator = tree.iterator();
  //Displaying the Tree set data
  while (iterator.hasNext()){
  System.out.print(iterator.next() + " ");
  }
  System.out.println();
  System.out.println("Now the size of tree set: " + tree.size());
  //Remove all
  tree.clear();
  if (tree.isEmpty()){
  System.out.print("Tree Set is empty.");
  }
  else{
  System.out.println("Tree Set size: " + tree.size());
  }
  }
}
Output of this program:
C:\vinod\collection>javac TreeSetExample.java

C:\vinod\collection>java TreeSetExample
Tree Set Example!

Tree set data: 12 23 34 45
Tree Set size: 4
First data: 12
Last data: 45
Data doesn't exist!
Now the tree set contain: 12 23 34 45
Now the size of tree set: 4
Tree Set is empty.

C:\vinod\collection>

Changes in Jar and Zip
http://www.roseindia.net/images/previous.gif    http://www.roseindia.net/images/bt_home.gif  http://www.roseindia.net/images/next.gif
In Java SE 6 there are two changes in jar command behavior:
  • Before Java SE 6, the timestamps (date and time) of extracted files by jar command are those listed the current time means extraction time instead of archive file time. But other de/compression tools use the archive time. So in Java SE 6, they do a change in jar command behavior that is the date and time of extracted files by jar command were the archive time. But if the old behavior is needed, use sun.tools.jar.useExtractionTime=true 
  • At the time of creating a jar, we have the ability in executable jar file to specify the entry point for stand-alone application bundle. The 'e' option declare the entry point through creating or overriding the Main-Class attribute value in the jar file's manifest.
There are some changes in ZIP File also:
  • Number of open ZIP files - Prior to Java SE 6, we faced the limitation on the number of concurrently open ZIP files in Microsoft Windows. And the maximum used to be 2306 but now this limitation has removed and the maximum used is depend on the whatever the platform will support.
  • Number of entries in a ZIP file - The ZIP file format was using 2-byte field to record the number of entries in the file, imposing a 64K limit. But in Java SE 6, ignores that field, just counts the entries. Before Java 6 you could count the entries with ZipInputStream or ZipFile, but if there were more than 64 entries in the file you get the different result.
  • ZIP File Names - Java SE 6 support the file names longer than 256 characters.
  • API Changes -  There are two new compressed streams have been added :
    1. java.util.zip.DeflaterInputStream - This stream is used to read the compressed data. For example, This stream can be useful if any client  want to send the data in compressed form over a network and it can compressed into packets by DeflaterInputStream.
    java.util.zip.InflaterOutputStream - This stream is used to write the decompressed data. For example, At the receiving end decompresses the compressed packet by writing to an InflaterOutputStream.

1 comment: