Monday, 7 March 2016

Java Collections FrameWork

Collection Framework

Collection framework was not 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. Collection framework 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 sets to handle sorted set.
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 means 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, now 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 Collection Framework

Exception NameDescription
UnSupportedOperationException          occurs 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 collection framework has a lot of Interfaces, setting the fundamental nature of various collection classes. Lets study the most important Interfaces in the collection 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,
  2. interface Collection < E >
    
  3. Following are some of the commonly used methods in this interface.
  4. MethodsDescription
    add( E obj )Used to add objects to a collection. Doesn't add duplicate elements to the collection.
    addAll( Collection C )Add all elements of collection C to the invoking collection
    remove( Object obj )To remove an object from collection
    removeAll( Collection C )Removes all element of collection C from the invoking collection
    contains( Object obj )To determine whether an object is present in collection or not
    isEmpty()Returns true if collection is empty, else returns false
    size()returns number of elements present in collection

The List Interface

  1. It extends the Collection Interface, and defines storage as sequence of elements. Following is its general declaration,
  2. interface List < E >
    
  3. Allows random access and insertion, based on position.
  4. It allows Duplicate elements.
  5. Apart from methods of Collection Interface, it adds following methods of its own.
  6. MethodsDescription
    get( int index )Returns object stored at the specified index
    set( int index, E obj)Stores object at the specified index in the calling collection
    indexOf( Object obj )Returns index of first occurence of obj in the collection
    lastIndexOf( Object obj )Returns index of last occurence of obj in the collection
    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,
  2. interface Set < E >
  3. It doesn't define any method of its own. It has two sub interfaces, SortedSet and NavigableSet.
  4. SortedSet interface extends Set interface and arranges added elements in an ascending order.
  5. 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,
  2. interface Queue < E >
  3. There are couple of new and interestin methods added by this interface. Some of them are mentioned in below table.
  4. MethodsDescription
    poll()removes element at the head of the queue and returns null if queue is empty
    remove()removes element at the head of the queue and throws NoSuchElementException if queue is empty
    peek()returns the element at the head of the queue without removing it. Returns null if queue is empty
    element()same as peek(), but throws NoSuchElementException if queue is empty
    offer( E obj )Adds object to queue.

The Dequeue Interface

  1. It extends Queue interface and declares behaviour of a double-ended queue. Its general declaration is,
  2. interface Dequeue < E >
  3. Double ended queues can function as simple queues as well as like standard Stacks.

The Collection classes

Java provides a set of Collection classes that implements Collection interface. Some of these classes provide full implementations that can be used as it is and other abstract classes provides skeletal implementations that can be used as starting points for creating concrete collections.

ArrayList class

  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.
  3. ArrayList()
    
    ArrayList( Collection C )
    
    ArrayList( int capacity )
    
  4. ArrayLists are created with an initial size, when this size is exceeded, it gets enlarged automatically.
  5. It can contain Duplicate elements and maintains the insertion order.
  6. ArrayLists are not synchronized.

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 araay containing all the contents of the list. Following are the reasons why you must obtain array from your ArrayList whenever required.
  • To obtain faster processing.
  • To pass array to methods who do not accept Collectionn as arguments.
  • To integrate and use collections with legacy code.

Storing User-Defined classes

In the above 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. It can be used as List, stack or Queue as it implements all the related interfaces.
  3. It can contain duplicate elements and is not synchronized.

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]

HashSet class

  1. HashSet extends AbstractSet class and implements the Set interface.
  2. It creates a collection that uses hash table for storage.
  3. HashSet does not maintain any order of 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.

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 elements sorted ascending order.
  3. Uses a Tree structure to store elements.
  4. Access and retrieval times are quite fast.
  5. It has four Constructors.
  6. TreeSet()
    
    TreeSet( Collection C )
    
    TreeSet( Comparator comp )
    
    TreeSet( SortedSet ss )
     

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 throught 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

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.
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 implement the List Interface.
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
     
 

1 comment: