08/11/2017
Collection Framework
admin admin

Collection Framework

Collections framework was not a part of original Java release. Collections was added to J2SE 1.2. Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties to store and manipulate groups of objects.

Framework in java means hierarchy of classes and interfaces.Collections framework is contained in java.util package. It provides many important classes and interfaces to collect and organize group of alike objects.


Important Interfaces of Collection API

InterfaceDescription
CollectionEnables you to work with groups of object; it is at the top of Collection hierarchy
DequeExtends Queue to handle double ended queue.
ListExtends Collection to handle sequences list of object.
QueueExtends Collection to handle special kind of list in which element are removed only from the head.
SetExtends Collection to handle sets, which must contain unique element.
SortedSetExtends Set to handle sorted set.

Collection Heirarchy

Collection Heirarchy

All these Interfaces give several methods which are defined by collections classes which implement these interfaces.


Why Collections were made Generic ?

Generics added type safety to Collection framework. Earlier collections stored Object class references which meant any collection could store any type of object. Hence there were chances of storing incompatible types in a collection, which could result in run time mismatch. Hence Generics was introduced through which you can explicitly state the type of object being stored.


Collections and Autoboxing

We have studied that Autoboxing converts primitive types into Wrapper class Objects. As collections doesn't store primitive data types(stores only refrences), hence Autoboxing facilitates the storing of primitive data types in collection by boxing it into its wrapper type.


Most Commonly thrown Exceptions in Collections Framework

Exception NameDescription
UnSupportedOperationExceptionoccurs if a Collection cannot be modified
ClassCastExceptionoccurs when one object is incompatible with another
NullPointerExceptionoccurs when you try to store null object in Collection
IllegalArgumentExceptionthrown if an invalid argument is used
IllegalStateExceptionthrown if you try to add an element to an already full Collection

Interfaces of Collection Framework

The Collections framework has a lot of Interfaces, setting the fundamental nature of various collection classes. Lets study the most important Interfaces in the Collections framework.


The Collection Interface

  1. It is at the top of collection heirarchy and must be implemented by any class that defines a collection. Its general declaration is,
    interface Collection < E >
    
  2. Following are some of the commonly used methods in this interface.
    MethodsDescription
    boolean add( E obj )Used to add objects to a collection. Returns true if obj was added to the collection. Returns false if obj is already a member of the collection, or if the collection does not allow duplicates.
    boolean addAll( Collection C )Add all elements of collection C to the invoking collection. Returns true if the element were added. Otherwise, returns false.
    boolean remove( Object obj )To remove an object from collection. Returns true if the element was removed. Otherwise, returns false.
    boolean removeAll( Collection C )Removes all element of collection C from the invoking collection. Returns true if the collection's elements were removed. Otherwise, returns false.
    boolean contains( Object obj )To determine whether an object is present in collection or not. Returns true if obj is an element of the invoking collection. Otherwise, returns false.
    boolean isEmpty()Returns true if collection is empty, else returns false.
    int size()Returns number of elements present in collection.
    void clear()Removes total number of elements from the collection.
    Object[] toArray()Returns an array which consists of the invoking collection elements.
    boolean retainAll(Collection c)Deletes all the elements of invoking collection except the specified collection.
    Iterator iterator( )Returns an iterator for the invoking collection.
    boolean equals(Object obj)Returns true if the invoking collection and obj are equal. Otherwise, returns false.
    Object[] toArray(Object array[])Returns an array containing only those collection elements whose type matches of the specified array.

The List Interface

  1. It extends the Collection Interface, and defines storage as sequence of elements. Following is its general declaration,
    interface List < E >
    
  2. Allows random access and insertion, based on position.
  3. It allows Duplicate elements.
  4. Apart from methods of Collection Interface, it adds following methods of its own.
    MethodsDescription
    Object get( int index )Returns object stored at the specified index
    Object set( int index, E obj)Stores object at the specified index in the calling collection
    int indexOf( Object obj )Returns index of first occurrence of obj in the collection
    int lastIndexOf( Object obj )Returns index of last occurrence of obj in the collection
    List subList( int start, int end )Returns a list containing elements between start and end index in the collection

The Set Interface

  1. This interface defines a Set. It extends Collection interface and doesn't allow insertion of duplicate elements. It's general declaration is,
    interface Set < E >
    
  2. It doesn't define any method of its own. It has two sub interfaces, SortedSet and NavigableSet.
  3. SortedSet interface extends Set interface and arranges added elements in an ascending order.
  4. NavigabeSet interface extends SortedSet interface, and allows retrieval of elements based on the closest match to a given value or values.

The Queue Interface

  1. It extends collection interface and defines behaviour of queue, that is first-in, first-out. It's general declaration is,
    interface Queue < E >
    
  2. There are couple of new and interesting methods added by this interface. Some of them are mentioned in below table.
    MethodsDescription
    Object poll()removes element at the head of the queue and returns null if queue is empty
    Object remove()removes element at the head of the queue and throws NoSuchElementException if queue is empty
    Object peek()returns the element at the head of the queue without removing it. Returns null if queue is empty
    Object element()same as peek(), but throws NoSuchElementException if queue is empty
    boolean offer( E obj )Adds object to queue.

The Dequeue Interface

  1. It extends Queue interface and implements behaviour of a double-ended queue. Its general declaration is,
    interface Dequeue < E >
    
  2. Since it implements Queue interface, it has the same methods as mentioned there.
  3. Double ended queues can function as simple queues as well as like standard Stacks.

The Collection classes

There are some standard classes that implements Collection interface. Some of the classes provide full implementations that can be used as it is.Others are abstract classes, which provides skeletal implementations that can be used as a starting point for creating concrete collections.

The standard collection classes are:

ClassDescription
AbstractCollectionImplements most of the Collection interface.
AbstractListExtends AbstractCollection and implements most of the List interface.
AbstractQueueExtends AbstractCollection and implements parts of the Queue interface.
AbstractSequentialListExtends AbstractList for use by a collection that uses sequential rather than random access of its elements.
LinkedListImplements a linked list by extending AbstractSequentialList
ArrayListImplements a dynamic array by extending AbstractList
ArrayDequeImplements a dynamic double-ended queue by extending AbstractCollection and implementing the Deque interface(Added by Java SE 6).
AbstractSetExtends AbstractCollection and implements most of the Set interface.
EnumSetExtends AbstractSet for use with enum elements.
HashSetExtends AbstractSet for use with a hash table.
LinkedHashSetExtends HashSet to allow insertion-order iterations.
PriorityQueueExtends AbstractQueue to support a priority-based queue.
TreeSetImplements a set stored in a tree. Extends AbstractSet.

Note:

  1. To use any Collection class in your program, you need to import it in your program. It is contained inside java.util package.
  2. Whenever you print any Collection class, it gets printed inside the square brackets [].

ArrayList class

Simple arrays have fixed size i.e it can store fixed number of elements. But, sometimes you may not know beforehand about the number of elements that you are going to store in your array. In such situations, We can use an ArrayList, which is an array whose size can increase or decrease dynamically.

  1. ArrayList class extends AbstractList class and implements the List interface.
  2. ArrayList supports dynamic array that can grow as needed. ArrayList has three constructors.
    ArrayList()  //It creates an empty ArrayList
    
    ArrayList( Collection C ) //It creates an ArrayList that is initialized with elements of the Collection C
    
    ArrayList( int capacity ) //It creates an ArrayList that has the specified initial capacity 
    
  3. ArrayLists are created with an initial size. When this size is exceeded, the size of the ArrayList increases automatically.
  4. It can contain Duplicate elements and it also maintains the insertion order.
  5. Manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the array list.
  6. ArrayLists are not synchronized.
  7. ArrayList allows random access because it works on the index basis.

Example of ArrayList

 
import java.util.*
class Test
{
 public static void main(String[] args)
 {
  ArrayList< String> al = new ArrayList< String>();
  al.add("ab");
  al.add("bc");
  al.add("cd");
  system.out.println(al);
 }
}

Output :

[ab,bc,cd]

Getting Array from an ArrayList

toArray() method is used to get an array containing all the contents of the ArrayList. Following are some reasons for why you can need to obtain an array from your ArrayList:

  • To obtain faster processing for certain operations.
  • To pass an array to methods which do not accept Collection as arguments.
  • To integrate and use collections with legacy code.

Storing User-Defined classes

In the above mentioned example we are storing only string object in ArrayList collection. But You can store any type of object, including object of class that you create in Collection classes.


Example of storing User-Defined object

Contact class

class Contact
{
    String first_name;
    String last_name;
    String phone_no;

    public Contact(String fn,String ln,String pn) 
    {
    first_name = fn;
    last_name = ln;
    phone_no = pn;
    }
    
    public String toString()
    {
        return first_name+" "+last_name+"("+phone_no+")";
    }
}

Storing Contact class

public class PhoneBook
{
    
   public static void main(String[] args) 
   {
       Contact c1 = new Contact("Ricky", "Pointing","999100091");
       Contact c2 = new Contact("David", "Beckham","998392819");
       Contact c3 = new Contact("Virat", "Kohli","998131319");
       
    ArrayList< Contact> al = new ArrayList< Contact>();	
     al.add(c1);
     al.add(c2);
     al.add(c3);
     System.out.println(al);
   }
    
}

Output:

[Ricky Pointing(999100091), David Beckham(998392819), Virat Kohli(998131319)]

LinkedList class

  1. LinkedList class extends AbstractSequentialList and implements List,Deque and Queue inteface.
  2. LinkedList has two constructors.
    LinkedList() //It creates an empty LinkedList
    
    LinkedList( Collection C ) //It creates a LinkedList that is initialized with elements of the Collection c
    
  3. It can be used as List, stack or Queue as it implements all the related interfaces.
  4. They are dynamic in nature i.e it allocates memory when required. Therefore insertion and deletion operations can be easily implemented.
  5. It can contain duplicate elements and it is not synchronized.
  6. Reverse Traversing is difficult in linked list.
  7. In LinkedList, manipulation is fast because no shifting needs to be occurred.

Example of LinkedList class

import java.util.* ;
class Test
{
 public static void main(String[] args)
 {
  LinkedList< String> ll = new LinkedList< String>();
  ll.add("a");
  ll.add("b");
  ll.add("c");
  ll.addLast("z");
  ll.addFirst("A");
  System.out.println(ll);
 }
}

Output:

[A, a, b,c, z]

Difference between ArrayList and Linked List

ArrayList and LinkedList are the Collection classes, and both of them implements the List interface. The ArrayList class creates the list which is internally stored in a dynamic array that grows or shrinks in size as the elements are added or deleted from it. LinkedList also creates the list which is internally stored in a DoublyLinked List. Both the classes are used to store the elements in the list, but the major difference between both the classes is that ArrayList allows random access to the elements in the list as it operates on an index-based data structure. On the other hand, the LinkedList does not allow random access as it does not have indexes to access elements directly, it has to traverse the list to retrieve or access an element from the list.

Some more differences:

  • ArrayList extends AbstarctList class whereas LinkedList extends AbstractSequentialList.
  • AbstractList implements List interface, thus it can behave as a list only whereas LinkedList implements List, Deque and Queue interface, thus it can behave as a Queue and List both.
  • In a list, access to elements is faster in ArrayList as random access is also possible. Access to LinkedList elements is slower as it follows sequential access only.
  • In a list, manipulation of elements is slower in ArrayList whereas it is faster in LinkedList.

HashSet class

  1. HashSet extends AbstractSet class and implements the Set interface.
  2. HashSet has three constructors.
  3. HashSet()  //This creates an empty HashSet
    
    HashSet( Collection C )  //This creates a HashSet that is initialized with the elements of the Collection C
    
    HashSet( int capacity )  //This creates a HashSet that has the specified initial capacity
    
  4. It creates a collection that uses hash table for storage. A hash table stores information by using a mechanism called hashing.
  5. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored.
  6. HashSet does not maintain any order of elements.
  7. HashSet contains only unique elements.

Example of HashSet class

import java.util.*;
class HashSetDemo
{
 public static void main(String args[])
 {
  HashSet< String> hs = new HashSet< String>();
  hs.add("B");
  hs.add("A");
  hs.add("D");
  hs.add("E");
  hs.add("C");
  hs.add("F");
  System.out.println(hs); 
 }
}

Output:

[D, E, F, A, B, C]

LinkedHashSet Class

  1. LinkedHashSet class extends HashSet class
  2. LinkedHashSet maintains a linked list of entries in the set.
  3. LinkedHashSet stores elements in the order in which elements are inserted i.e it maintains the insertion order.

Example of LinkedHashSet class

import java.util.*;
class LinkedHashSetDemo
{
 public static void main(String args[])
 {
  LinkedHashSet< String> hs = new LinkedHashSet< String>();
  hs.add("B");
  hs.add("A");
  hs.add("D");
  hs.add("E");
  hs.add("C");
  hs.add("F");
  System.out.println(hs); 
 }
}

Output :

[B, A, D, E, C, F]

TreeSet Class

  1. It extends AbstractSet class and implements the NavigableSet interface.
  2. It stores the elements in ascending order.
  3. It uses a Tree structure to store elements.
  4. It contains unique elements only like HashSet.
  5. It's access and retrieval times are quite fast.
  6. It has four Constructors.
  7. TreeSet()  //It creates an empty tree set that will be sorted in an ascending order according to the
    natural order of the tree set
    
    TreeSet( Collection C )  //It creates a new tree set that contains the elements of the Collection C
    
    TreeSet( Comparator comp )  //It creates an empty tree set that will be sorted according to given Comparator
    
    TreeSet( SortedSet ss )  //It creates a TreeSet that contains the elements of given SortedSet
    

Example of TreeSet class

import java.util.*;
class TestCollection11{
 public static void main(String args[]){
   TreeSet al=new TreeSet();
   al.add("Ravi");
   al.add("Vijay");
  al.add("Ravi");
  al.add("Ajay");

  Iterator itr=al.iterator();
  while(itr.hasNext()){
   System.out.println(itr.next());
  }
 }
}

Output :

Ajay
Ravi
Vijay

PriorityQueue Class

  1. It extends the AbstractQueue class.
  2. The PriorityQueue class provides the facility of using queue.
  3. It does not orders the elements in FIFO manner.
  4. PriorityQueue has six constructors. In all cases, the capacity grows automatically as elements are added.
    PriorityQueue( )  //This constructor creates an empty queue. By default, its starting capacity is 11
    
    PriorityQueue(int capacity) //This constructor creates a queue that has the specified initial capacity
    
    PriorityQueue(int capacity, Comparator comp) //This constructor creates a queue with the specified capacity
    and comparator
    
    //The last three constructors create queues that are initialized with elements of Collection passed in c
    PriorityQueue(Collection c) 
    
    PriorityQueue(PriorityQueue c)
    
    PriorityQueue(SortedSet c)
    

Note: If no comparator is specified when a PriorityQueue is constructed, then the default comparator for the type of data stored in the queue is used. The default comparator will order the queue in ascending order. Thus, the head of the queue will be the smallest value. However, by providing a custom comparator, you can specify a different ordering scheme.

Note: Although you can iterate through a PriorityQueue using an iterator, the order of that iteration is undefined. To properly use a PriorityQueue, you must call methods such as offer( ) and poll( ), which are defined by the Queue interface.


Example of PriorityQueue class

import java.util.*; 

class StudyTonight
{ 
public static void main(String args[])
{ 
  PriorityQueue queue=new PriorityQueue(); 
  queue.add("WE"); 
  queue.add("LOVE"); 
  queue.add("STUDY"); 
  queue.add("TONIGHT");   
  System.out.println("At head of the queue:"+queue.element()); 
  System.out.println("At head of the queue:"+queue.peek()); 
  System.out.println("Iterating the queue elements:"); 
  Iterator itr=queue.iterator(); 
  while(itr.hasNext()){ 
    System.out.println(itr.next()); 
  } 
  queue.remove(); 
  queue.poll(); 
  System.out.println("After removing two elements:"); 
  Iterator itr2=queue.iterator(); 
  while(itr2.hasNext()){ 
    System.out.println(itr2.next()); 
  } 
} 
} 

Output :

At head of the queue:LOVE
At head of the queue:LOVE
Iterating the queue elements:
LOVE
TONIGHT
STUDY
WE
After removing two elements:
TONIGHT
WE

Accessing a Collection

To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle through the elements of the collection. There are three possible ways to cycle through the elements of any collection.

  1. Using Iterator interface
  2. Using ListIterator interface
  3. Using for-each loop

Steps to use an Iterator

  1. Obtain an iterator to the start of the collection by calling the collection's iterator() method.
  2. Set up a loop that makes a call to hasNext() method. Make the loop iterate as long as hasNext( ) method returns true.
  3. Within the loop, obtain each element by calling next() method.

Accessing elements using Iterator

Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements of the collection. Each collection classes provide iterator() method to return an iterator.

Methods of Iterator:

MethodDescription
boolean hasNext()Returns true if there are more elements in the collection. Otherwise, returns false.
E next()Returns the next element present in the collection. Throws NoSuchElementException if there is not a next element.
void remove()Removes the current element. Throws IllegalStateException if an attempt is made to call remove() method that is not preceded by a call to next() method.

import java.util.*;
class Test_Iterator
{
 public static void main(String[] args)
 {
  ArrayList< String> ar = new ArrayList< String>();
  ar.add("ab");
  ar.add("bc");
  ar.add("cd");
  ar.add("de");

 Iterator it = ar.iterator();     //Declaring Iterator
  while(it.hasNext())
  {  
   System.out.print(it.next()+" ");
  }
 }
}

Output :

ab bc cd de

Accessing element using ListIterator

ListIterator Interface is used to traverse a list in both forward and backward direction. It is available to only those collections that implements the List Interface.

Methods of ListIterator:

MethodDescription
void add(E obj)Inserts obj into the list in front of the element that will be returned by the next call to next() method.
boolean hasNext()Returns true if there is a next element. Otherwise, returns false.
boolean hasPrevious()Returns true if there is a previous element. Otherwise, returns false.
E next()Returns the next element. A NoSuchElementException is thrown if there is not a next element.
int nextIndex()Returns the index of the next element. If there is not a next element, returns the size of the list.
E previous()Returns the previous element. A NoSuchElementException is thrown if there is not a previous element.
int previousIndex()Returns the index of the previous element. If there is not a previous element, returns -1.
void remove()Removes the current element from the list. An IllegalStateException is thrown if remove() method is called before next() or previous() method is invoked.
void set(E obj)Assigns obj to the current element. This is the element last returned by a call to either next() or previous() method.

import java.util.*;
class Test_Iterator
{
 public static void main(String[] args)
 {
  ArrayList< String> ar = new ArrayList< String>();
  ar.add("ab");
  ar.add("bc");
  ar.add("cd");
  ar.add("de");

  ListIterator litr = ar.listIterator();
  while(litr.hasNext())                 //In forward direction
  {
   System.out.print(litr.next()+" ");
  }

  while(litr.hasPrevious())             //In backward direction
  {
   System.out.print(litr.next()+" ");
  }
 }
}

Output :

  ab bc cd de
  de cd bc ab

Using for-each loop

for-each version of for loop can also be used for traversing each element of a collection. But this can only be used if we don't want to modify the contents of a collection and we don't want any reverse access. for-each loop can cycle through any collection of object that implements Iterable interface.

import java.util.*;
class ForEachDemo
{
 public static void main(String[] args)
 {
  LinkedList< String> ls = new LinkedList< String>();
  ls.add("a");
  ls.add("b");
  ls.add("c");
  ls.add("d");
  
  for(String str : ls)
  {
   System.out.print(str+" ");
  }
 }
}

Output :

a b c d 

Map Interface

A Map stores data in key and value association. Both key and values are objects. The key must be unique but the values can be duplicate. Although Maps are a part of Collection Framework, they can not actually be called as collections because of some properties that they posses. However we can obtain a collection-viewof maps.

InterfaceDescription
MapMaps unique key to value.
Map.EntryDescribe an element in key and value pair in a map. Entry is sub interface of Map.
NavigableMapExtends SortedMap to handle the retrienal of entries based on closest match searches
SortedMapExtends Map so that key are maintained in an ascending order.

map interface sub interfaces


Commonly used Methods defined by Map

  • boolean containsKey(Object k): returns true if map contain k as key. Otherwise false.
  • Object get(Object k) : returns values associated with the key k.
  • Object put(Object k, Object v) : stores an entry in map.
  • Object putAll(Map m) : put all entries from m in this map.
  • Set keySet() : returns Set that contains the key in a map.
  • Set entrySet() : returns Set that contains the entries in a map.

HashMap class

  1. HashMap class extends AbstractMap and implements Map interface.
  2. It uses a hashtable to store the map. This allows the execution time of get() and put() to remain same.
  3. HashMap has four constructor.
    HashMap()
    HashMap(Map< ? extends k, ? extends V> m)
    HashMap(int capacity)
    HashMap(int capacity, float fillratio)
    
  4. HashMap does not maintain order of its element.

Example

import java.util.*;
class HashMapDemo
{
 public static void main(String args[])
 {
  HashMap< String,Integer> hm = new HashMap< String,Integer>();
  hm.put("a",new Integer(100));
  hm.put("b",new Integer(200));
  hm.put("c",new Integer(300));
  hm.put("d",new Integer(400));

  Set< Map.Entry< String,Integer> > st = hm.entrySet();    //returns Set view
  for(Map.Entry< String,Integer> me:st)
  {
   System.out.print(me.getKey()+":");
   System.out.println(me.getValue());
  }
 }
}

Output :

c 300
a 100
d 400
b 200

TreeMap class

  1. TreeMap class extends AbstractMap and implements NavigableMap interface.
  2. It creates Map, stored in a tree structure.
  3. TreeMap provides an efficient means of storing key/value pair in efficient order.
  4. It provides key/value pairs in sorted order and allows rapid retrieval.

Example

import java.util.*;
class TreeMapDemo
{
 public static void main(String args[])
 {
  TreeMap< String,Integer> tm = new TreeMap< String,Integer>();
  tm.put("a",new Integer(100));
  tm.put("b",new Integer(200));
  tm.put("c",new Integer(300));
  tm.put("d",new Integer(400));

  Set< Map.Entry< String,Integer> > st = tm.entrySet();
  for(Map.Entry me:st)  
  {
   System.out.print(me.getKey()+":");
   System.out.println(me.getValue());
  }
 }
}

Output :

a 100
b 200
c 300
d 400

LinkedHashMap class

  1. LinkedHashMap extends HashMap class.
  2. It maintains a linked list of entries in map in order in which they are inserted.
  3. LinkedHashMap defines the following constructor
    LinkedHashMap()
    
    LinkedHashMap(Map< ? extends k, ? extends V> m)
    
    LinkedHashMap(int capacity)
    
    LinkedHashMap(int capacity, float fillratio)
    
    LinkedHashMap(int capacity, float fillratio, boolean order)
    
  4. It adds one new method removeEldestEntry(). This method is called by put() and putAll() By default this method does nothing. However we can override this method to remove oldest element in the map. Syntax
    protected boolean removeEldestEntry(Map.Entry e)
    

EnumMap class

  1. EnumMap extends AbstractMap and implements Map interface.
  2. It is used for key as enum

    Comparator Interface

    In Java, Comparator interface is used to order(sort) the objects in the collection in your own way. It gives you the ability to decide how elements will be sorted and stored within collection and map.

    Comparator Interface defines compare() method. This method has two parameters. This method compares the two objects passed in the parameter. It returns 0 if two objects are equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is returned. The method can throw a ClassCastException if the type of object are not compatible for comparison.


    Rules for using Comparator interface

    Rules for using Comparator interface:

    1. If you want to sort the elements of a collection, you need to implement Comparator interface.
    2. If you do not specify the type of the object in your Comparator interface, then, by default, it assumes that you are going to sort the objects of type Object. Thus, when you override the compare() method ,you will need to specify the type of the parameter as Object only.
    3. If you want to sort the user-defined type elements, then while implementing the Comparator interface, you need to specify the user-defined type generically. If you do not specify the user-defined type while implementing the interface,then by default, it assumes Object type and you will not be able to compare the user-defined type elements in the collection

    For Example:

    If you want to sort the elements according to roll number, defined inside the class Student, then while implementing the Comparator interface, you need to mention it generically as follows:

    class MyComparator implements Comparator<Student>{}

    If you write only,

    class MyComparator implements Comparator {}

    Then it assumes, by default, data type of the compare() method's parameter to be Object, and hence you will not be able to compare the Student type(user-defined type) objects.


    Example

    Student class

    class Student
    int roll;
      String name;
      Student(int r,String n)
      {
          roll = r;
          name = n;
      }
      public String toString()
      {
          return roll+" "+name;
      }
    

    MyComparator class

    This class defines the comparison logic for Student class based on their roll. Student object will be sorted in ascending order of their roll.

    class MyComparator implements Comparator<Student>
    {
      public int compare(Student s1,Student s2)
        {
            if(s1.roll == s2.roll) return 0;
            else if(s1.roll > s2.roll) return 1;
            else return -1;
        }  
    }
    
    public class Test 
    {
        
       public static void main(String[] args) 
       {
           TreeSet< Student> ts = new TreeSet< Student>(new MyComparator());
           ts.add(new Student(45, "Rahul"));
           ts.add(new Student(11, "Adam"));
           ts.add(new Student(19, "Alex"));
           System.out.println(ts);
       }
        
    }
    

    Output :

    [ 11 Adam, 19 Alex, 45 Rahul ]
    

    As you can see in the ouput Student object are stored in ascending order of their roll.


    Note:

    • When we are sorting elements in a collection using Comparator interface, we need to pass the class object that implements Comparator interface.
    • To sort a TreeSet collection, this object needs to be passed in the constructor of TreeSet.
    • If any other collection, like ArrayList,was used, then we need to call sort method of Collections class and pass the name of the collection and this object as a parameter.
    • For example, If the above program used ArrayList collection, the public class test would be as follows:
    public class Test
    {  
       public static void main(String[] args)
       {
           ArrayList< Student> ts = new ArrayList< Student>();
           ts.add(new Student(45, "Rahul"));
           ts.add(new Student(11, "Adam"));
           ts.add(new Student(19, "Alex"));
           Collections.sort(ts,new MyComparator()); /*passing the name of the ArrayList and the
    object of the class that implements Comparator in a predefined sort() method in Collections
    class*/
           System.out.println(ts);
       }   
    }
    

    Legacy Classes

    Early version of java did not include the Collections framework. It only defined several classes and interfaces that provide methods for storing objects. When Collections framework were added in J2SE 1.2, the original classes were reengineered to support the collection interface. These classes are also known as Legacy classes. All legacy classes and interface were redesign by JDK 5 to support Generics. In general, the legacy classes are supported because there is still some code that uses them.

    The following are the legacy classes defined by java.util package

    1. Dictionary
    2. HashTable
    3. Properties
    4. Stack
    5. Vector

    There is only one legacy interface called Enumeration

    NOTE: All the legacy classes are synchronized


    Enumeration interface

    1. Enumeration interface defines method to enumerate(obtain one at a time) through collection of objects.
    2. This interface is superseded(replaced) by Iterator interface.
    3. However, some legacy classes such as Vector and Properties defines several method in which Enumeration interface is used.
    4. It specifies the following two methods
    5. boolean hasMoreElements() //It returns true while there are still more elements to extract,
      and returns false when all the elements have been enumerated.
      
      Object nextElement() //It returns the next object in the enumeration i.e. each call to nextElement() method
      obtains the next object in the enumeration. It throws NoSuchElementException when the
      enumeration is complete.
      

    Vector class

    1. Vector is similar to ArrayList which represents a dynamic array.
    2. There are two differences between Vector and ArrayList. First, Vector is synchronized while ArrayList is not, and Second, it contains many legacy methods that are not part of the Collections Framework.
    3. With the release of JDK 5, Vector also implements Iterable. This means that Vector is fully compatible with collections, and a Vector can have its contents iterated by the for-each loop.
    4. Vector class has following four constructor
      Vector() //This creates a default vector, which has an initial size of 10.
      
      Vector(int size) //This creates a vector whose initial capacity is specified by size.
      
      Vector(int size, int incr) //This creates a vector whose initial capacity is specified by size and whose
      increment is specified by incr. The increment specifies the number of elements to allocate each time
      when a vector is resized for addition of objects.
      
      Vector(Collection c) //This creates a vector that contains the elements of collection c.
      

    Vector defines several legacy methods. Lets see some important legacy methods defined by Vector class.

    MethodDescription
    void addElement(E element)adds element to the Vector
    E elementAt(int index)returns the element at specified index
    Enumeration elements()returns an enumeration of element in vector
    E firstElement()returns first element in the Vector
    E lastElement()returns last element in the Vector
    void removeAllElements()removes all elements of the Vector

    Example of Vector

    import java.util.*;
    public class Test 
    {
      public static void main(String[] args) 
       {
          Vector ve = new Vector();
           ve.add(10);
           ve.add(20);
           ve.add(30);
           ve.add(40);
           ve.add(50);
           ve.add(60);
           
           Enumeration en = ve.elements();
           
           while(en.hasMoreElements())
           {
               System.out.println(en.nextElement());
           }
       }
        
    }
    

    Output :

    10
    20
    30
    40
    50
    60
    

    Hashtable class

    1. Like HashMap, Hashtable also stores key/value pair. However neither keys nor values can be null.
    2. There is one more difference between HashMap and Hashtable that is Hashtable is synchronized while HashMap is not.
    3. Hashtable has following four constructor
      Hashtable() //This is the default constructor. The default size is 11.
      
      Hashtable(int size) //This creates a hash table that has an initial size specified by size.
      
      Hashtable(int size, float fillratio) //This creates a hash table that has an initial size specified by size
      and a fill ratio specified by fillRatio. This ratio must be between 0.0 and 1.0, and it determines how full
      the hash table can be before it is resized upward. Specifically, when the number of elements is greater
      than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded.
      If you do not specify a fill ratio, then 0.75 is used.
      
      Hashtable(Map< ? extends K, ? extends V> m) //This creates a hash table that is initialized with the
      elements in m. The capacity of the hash table is set to twice the number of elements in m.
      The default load factor of 0.75 is used.
      

    Example of Hashtable

    import java.util.*;
    class HashTableDemo
    {
     public static void main(String args[])
     {
      Hashtable< String,Integer> ht = new Hashtable< String,Integer>();
      ht.put("a",new Integer(100));
      ht.put("b",new Integer(200));
      ht.put("c",new Integer(300));
      ht.put("d",new Integer(400));
    
      Set st = ht.entrySet();
      Iterator itr=st.iterator();
      while(itr.hasNext())
      {
       Map.Entry m=(Map.Entry)itr.next();
       System.out.println(itr.getKey()+" "+itr.getValue());
      }
     }
    }
    

    Output:

    a 100
    b 200
    c 300
    d 400
    

    Difference between HashMap and Hashtable

    HashtableHashMap
    Hashtable class is synchronized.HashMap is not synchronized.
    Because of Thread-safe, Hashtable is slower than HashMapHashMap works faster.
    Neither key nor values can be nullBoth key and values can be null
    Order of table remain constant over time.does not guarantee that order of map will remain constant over time.

    Properties class

    1. Properties class extends Hashtable class.
    2. It is used to maintain list of value in which both key and value are String
    3. Properties class define two constructor
      Properties() //This creates a Properties object that has no default values
      
      Properties(Properties propdefault) //This creates an object that uses propdefault for its default values.
      
    4. One advantage of Properties over Hashtable is that we can specify a default property that will be useful when no value is associated with a certain key.
    5. Note: In both cases, the property list is empty

    6. In Properties class, you can specify a default property that will be returned if no value is associated with a certain key.

    Example of Properties class

    import java.util.*;
    
    public class Test 
    {
        
       public static void main(String[] args) 
       {
         Properties pr = new Properties();
         pr.put("Java", "James Ghosling");
         pr.put("C++", "Bjarne Stroustrup");
         pr.put("C", "Dennis Ritchie");
         pr.put("C#", "Microsoft Inc.");
         Set< ?> creator = pr.keySet();
         
         for(Object ob: creator)
         {
             System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );
         }
         
       }
        
    }
    

    Output :

    Java was created by James Ghosling
    C++ was created by Bjarne Stroustrup
    C was created by Dennis Ritchie
    C# was created by Microsoft Inc
    

    Stack class

    1. Stack class extends Vector.
    2. It follows last-in, first-out principle for the stack elements.
    3. It defines only one default constructor
      Stack() //This creates an empty stack
    4. If you want to put an object on the top of the stack, call push() method. If you want to remove and return the top element, call pop() method. An EmptyStackException is thrown if you call pop() method when the invoking stack is empty.

    You can use peek() method to return, but not remove, the top object. The empty() method returns true if nothing is on the stack. The search() method determines whether an object exists on the stack and returns the number of pops that are required to bring it to the top of the stack.


    Example of Stack

    import java.util.*;
    
    class StackDemo {
    public static void main(String args[]) {
    Stack st = new Stack();
    st.push(11);
    st.push(22);
    st.push(33);
    st.push(44);
    st.push(55);
    Enumeration e1 = st.elements();
          
    while(e1.hasMoreElements())
    System.out.print(e1.nextElement()+" ");
    
    st.pop();
    st.pop();
    
    System.out.println("\nAfter popping out two elements");
    
    Enumeration e2 = st.elements();
    
    while(e2.hasMoreElements())
    System.out.print(e2.nextElement()+" ");
    
    }
    }
    

    Output:

    11 22 33 44 55
    After popping out two elements
    11 22 33
    

    Dictionary class

    1. Dictionary is an abstract class.
    2. It represents a key/value pair and operates much like Map.
    3. Although it is not currently deprecated, Dictionary is classified as obsolete, because it is fully superseded by Map class.

  • VIA
  • admin
  • TAGS



LEAVE A COMMENT

Facebook Conversations

FOLLOW US