Friday, January 2, 2015

Java Collection classes

Collection Framework provides an architecture to store and manipulate the group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, deletion etc. can be performed by Java Collection Framework.

Collection simply means a single unit of objects. Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).


Iterator interface

Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:
  1. public boolean hasNext() it returns true if iterator has more elements.
  2. public object next() it returns the element and moves the cursor pointer to the next element.
  3. public void remove() it removes the last elements returned by the iterator. It is rarely used.
ArrayList Class:
  • uses a dynamic array for storing the elements. It extends AbstractList class and implements List interface.
  • can contain duplicate elements.
  • maintains insertion order.
  • not synchronized. not thread-safe.
  • random access because array works at the index basis.
  • manipulation slow because a lot of shifting needs to be occurred.
Example:


import java.util.*;  
class Simple{  
 public static void main(String args[]){  
  // this form of creating ArayList will accept any object to add
  // this is because, add method accepts a parameter of type Object. 
  ArrayList al=new ArrayList();  
  al.add("Ravi");  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add(1.2f); // adding floating point number to ArrayList
  al.add(2);   // adding integer to ArrayList
  
  Iterator itr=al.iterator();  
  while(itr.hasNext()){  
   System.out.println(itr.next());  
  }  
 }  
}

Two ways to iterate the elements of collection:
a. Using Iterator interface.
b. Using for-each loop.

for(Object obj:al) {
    System.out.println(obj);  
}

Creating a parameterized ArrayList:

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
    public static void main(String[] args) {
        ArrayList al = new ArrayList();
        al.add("raghu");
        al.add("ramya");
        al.add("raghu");
        al.add(2);
        al.add(1.2f);
        
        Iterator it = al.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }       
        
        // this ArrayList only accepts Strings.
        ArrayList<String> als = new ArrayList<String>();
        als.add("raghunath");
        als.add("srinath");
        // als.add(1.2f); // gives compilation error
        
        for(String name: als)
            System.out.println(name);
    }            
}

LinkedList Class:
  • uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces.
  • can contain duplicate elements.
  • maintains insertion order.
  • not synchronized. not thread-safe.
  • No random access.
  • manipulation fast because no shifting needs to be occurred.
  • can be used as list, stack or queue.
Example:

import java.util.Iterator;
import java.util.LinkedList;

public class LinkedListExample {
    public static void main(String[] args) {
        LinkedList al = new LinkedList();
        al.add("raghu");
        al.add("ramya");
        al.add("raghu");
        al.add(2);
        al.add(1.2f);
        
        Iterator it = al.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }       
        
        LinkedList<String> als = new LinkedList<String>();
        als.add("raghunath");
        als.add("srinath");
        
        for(String name: als)
            System.out.println(name);
    }    
}

ListIterator Interface:

ListIterator Interface is used to traverse the element in backward and forward direction.

Methods:
  1. public boolean hasNext();
  2. public Object next();
  3. public boolean hasPrevious();
  4. public Object previous();
Example:

        LinkedList<String> als = new LinkedList<String>();
        als.add("raghunath");
        als.add("srinath");
        
        for(String name: als)
            System.out.println(name);

        Iterator it = als.iterator();
        while(it.hasNext()) {
            System.out.println(it.next());
        }
        
        System.out.println("Foward Iteration:");
        
        ListIterator fli = als.listIterator();
        while(fli.hasNext())
            System.out.println(fli.next());
        
        System.out.println("Backward Iteration:");

        ListIterator bli = als.listIterator(2);
        while(bli.hasPrevious())
            System.out.println(bli.previous());

HashSet Class:

The main difference between list and set is, set contain unique elements only. No duplicates are allowed in Set.
  • uses hashtable to store the elements.It extends AbstractSet class and implements Set interface.
  • contains unique elements only.
  • HashSet does not preserve element insertion order.  Insertion order is not maintained. To maintain insertion order, please use LinkedHashSet.
import java.util.HashSet;
import java.util.Iterator;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet hs = new HashSet();
        hs.add("raghu");
        hs.add("ramya");
        hs.add("ajay");
        hs.add("vinay");
        hs.add("raghu");
        hs.add("srinath");
        hs.add("vinay");
        
        Iterator it = hs.iterator();
        while(it.hasNext())
            System.out.println(it.next());        
    }
}

o/p: You can see here, the duplicates are not printed. Also, items are in random order.
vinay
raghu
srinath
ajay
ramya

LinkedHashSet Class:
  • contains unique elements only like HashSet. It extends HashSet class and implements Set interface.
  • removes duplicates but maintains insertion order.
Example:

        LinkedHashSet al=new LinkedHashSet();  
        al.add("Ravi");  
        al.add("Vijay");  
        al.add("Ravi");  
        al.add("Ajay");  

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

TreeSet Class:
  • contains unique elements only like HashSet. The TreeSet class implements NavigableSet interface that extends the SortedSet interface.
  • removes duplicates but maintains ascending order.
        TreeSet ts = new TreeSet();  
        ts.add("Ravi");  
        ts.add("Vijay");  
        ts.add("Ravi");  
        ts.add("Ajay");  

        Iterator titr=ts.iterator();  
        while(titr.hasNext()){  
         System.out.println(titr.next());  
        }














No comments:

Post a Comment