Sunday, August 26, 2012

Java Collection

Collections framework is used in java to store a group of objects.

In Collections framework the most important interface is Collection interface.
Collection interface has some important methods to add,remove,update and search objects.

Collection interface methods are as follows

int size()   : This method is used to check the size of the collection  
boolean isEmpty() : this method is used to check whether the collection contains any object or not
boolean contains(Object obj) :This method is used to search obj object in the collection
boolean containsAll(Collection<?> c) : Returns true if this collection contains all of the elements in the specified collection c.
boolean equals(Object other) : Checks equality with the other object
boolean addAll(Collection<? extends E> from) : Adds all the from collection into this collec
boolean remove(Object obj) : obj Object is removed from the collection
boolean removeAll(Collection<?> c) : Remove all the objects of c collection from this collection if exists.
void clear() : Cleans the collection and empty the collection
boolean retainAll(Collection<?> c) : Retains only the elements in this collection that are contained in the specified collection (optional operation). In other words, removes from this collection all of its elements that are not contained in the specified collection.
Object[] toArray() : This method is used to convert collection into an object array.


List,Set and Queue interfaces extends collection interface.

List : used to store things in ordered form.
Set : used to store unique objects only
Queue : used to store objects as per need basis .

Map is an interface which is used to store objects in key value pair.








hashcode() and equals method in Java
Whenever we create a class in java it automatically extends Object class.
We don't need to explicitly mention this on our own class.We need to override these two methods when we are creating our own class and the instances of that class is going to be added in a collection class.
Object class has 2 important methods hashcode() and equals() which were interlinked too.
A contract between hashcode() and equals is that a given object must consistently report the same hash value and that two objects which equals() says are equal must report the same hash value.

 hashcode() values are used to store an object in collection objects and also it is useful to retrieve an object from collection object. A collection which uses hashing algorithm it uses the hashcode() value to
find the proper bucket and if more than one object exista in that bucket then it checks the equality with the objects using equal function.

 toString()
It's an important method  of Object class. We need to override this method when we need a meaningful output while printing this object by default it returns object hashcode() value as output.


Now let us discuss about the interfaces in details and their concrete implemention.

List : List is used to store elements based on index. Values can be retrieved from a specific index.


Examples : If we are going to implement Bookshelf for storing books in ordered form we can use List.










ArrayList :
                 Implements List interface.
                 It has no size limit like array.
                 Elements are stored in ordered way bot not sorted.
                 It's used for fast retrieval of elements but slow insertion and deletion than linked list

Vector :  It's same as ArrayList .The only difference is its thread safe so in multithreaded environment
               it's better to use.It's a legacy class.

LinkedList : Elements are ordered not sorted.
                   Elements are doubly linked with another.
                   Provides methos to add or remove from head or tail.
                   Fast insertion and deletion but slow retrieval.

CodeExample :

package com.fastlearned;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;

public class ListExample {

 public void arrayListMethod() {
  // creating an arraylist
  List arrayList = new ArrayList();
  for (int i = 0; i < 5; i++) {
   arrayList.add("Book" + i);
  }

  System.out.println("ARRAYLIST 1st pos " + arrayList.get(0));
  System.out.println("ARRAYLIST 3rd pos " + arrayList.get(2));

 }

 public void vectorMethod() {
  {
   // creating an Vector
   List vectorList = new Vector();
   for (int i = 0; i < 5; i++) {
    vectorList.add("Book" + i);
   }

   System.out.println("VECTOR 1st pos " + vectorList.get(0));
   System.out.println("VECTOR 3rd pos " + vectorList.get(2));

  }
 }

 public void linkedListMethod() {
  {
   // creating an LinkedList
   List linkList = new LinkedList();
   for (int i = 0; i < 5; i++) {
    linkList.add("Book" + i);
   }

   System.out.println("LINKEDLIST 1st pos " + linkList.get(0));
   System.out.println("LINKEDLIST 3rd pos " + linkList.get(2));

  }
 }

 /**
  * @param args
  */
 public static void main(String[] args) {

  ListExample example = new ListExample();
  example.arrayListMethod();
  example.vectorMethod();
  example.linkedListMethod();

 }

}

Output :
ARRAYLIST 1st pos Book0
ARRAYLIST 3rd pos Book2
VECTOR 1st pos Book0
VECTOR 3rd pos Book2
LINKEDLIST 1st pos Book0
LINKEDLIST 3rd pos Book2


Set : Used to store unique elements so no duplicate values are allowed to store in a set.


Example :  We can use set for implementing an aquarium full of fishes with unique color only.
HashSet :
            Elements are stored as unordered and unsorted.
            Elements are stored using hashing algorithm.
            Each object has a hashcode value which is used to used to inserting or
           retrieving an element from a set.

LinkedHashSet :
                            It  maintains insertion order.
                            It's unsorted Set.
                            Maintain doubly linked list across elements.

TreeSet :
                       It is a sorted set.
                       It uses natural ordering or rather say ascending order.
                     

Code Example :
package com.fastlearned;

import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;

public class SetExample {

 public void hashSetMethod() {
  Set<fish> hset = new HashSet<fish>();
  hset.add(new Fish("RED"));
  hset.add(new Fish("YELLOW"));
  hset.add(new Fish("PURPLE"));
  hset.add(new Fish("GREEN"));

  // adding two more fishes of same color
  hset.add(new Fish("RED"));
  hset.add(new Fish("PURPLE"));

  Iterator<fish> fishIterator = hset.iterator();
  while (fishIterator.hasNext()) {
   System.out.println("HashSet = " + fishIterator.next());
  }

 }

 public void linkedHashSetMethod() {
  Set<fish> hset = new LinkedHashSet<fish>();
  hset.add(new Fish("RED"));
  hset.add(new Fish("YELLOW"));
  hset.add(new Fish("PURPLE"));
  hset.add(new Fish("GREEN"));

  // adding two more fishes of same color
  hset.add(new Fish("RED"));
  hset.add(new Fish("PURPLE"));

  Iterator<fish> fishIterator = hset.iterator();
  while (fishIterator.hasNext()) {
   System.out.println("LinkedHashSet() = " + fishIterator.next());
  }

 }

 public void treeSetMethod() {
  Set<fish> hset = new TreeSet<fish>();
  hset.add(new Fish("RED"));
  hset.add(new Fish("YELLOW"));
  hset.add(new Fish("PURPLE"));
  hset.add(new Fish("GREEN"));

  // adding two more fishes of same color
  hset.add(new Fish("RED"));
  hset.add(new Fish("PURPLE"));

  Iterator<fish> fishIterator = hset.iterator();
  while (fishIterator.hasNext()) {
   System.out.println("TreeSet() = " + fishIterator.next());
  }

 }

 /**
  * @param args
  */
 public static void main(String[] args) {

  SetExample setExample = new SetExample();
  setExample.hashSetMethod();
  setExample.linkedHashSetMethod();
  setExample.treeSetMethod();

 }

 class Fish implements Comparable<fish> {
  String color;

  public Fish(String _color) {
   color = _color;

  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + getOuterType().hashCode();
   result = prime * result + ((color == null) ? 0 : color.hashCode());
   return result;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   Fish other = (Fish) obj;
   if (!getOuterType().equals(other.getOuterType()))
    return false;
   if (color == null) {
    if (other.color != null)
     return false;
   } else if (!color.equals(other.color))
    return false;
   return true;
  }

  @Override
  public String toString() {

   return color;
  }

  private SetExample getOuterType() {
   return SetExample.this;
  }

  @Override
  public int compareTo(Fish o) {

   return color.compareTo(o.color);
  }

 }

}
Output :
HashSet = GREEN
HashSet = PURPLE
HashSet = YELLOW
HashSet = RED
LinkedHashSet() = RED
LinkedHashSet() = YELLOW
LinkedHashSet() = PURPLE
LinkedHashSet() = GREEN
TreeSet() = GREEN
TreeSet() = PURPLE
TreeSet() = RED
TreeSet() = YELLOW


Why do we need to implement  Comparable interface ?
When the instance of our own class is used in a Sorted collection we need to implement the interface
Comparable as the method compareTo() of Comparable is used to compare objects for sorting purpose.Example of sorted class Collection  are TreeMap,TreeSet.
We have utility functions of Collection object sorting as Collections.sort(collection)  and Array object sorting as Arrays.sort(arrayObject).We need to implement the Comparable interface if we are using these sorting functions.

Map :  Map interface is used to store elements in key value pair.


HashMap : HashMap is used to store key,value pair using hashing algorithm.
                   HashMap is an unordered and unsorted Map.
                   Elements hashcode() funtion is used to store and retrieve elements.
                   One null key and multiple null values can be inserted in a HashMap.
                   HashMap is the fastest Map for element adding and removing.
HashTable : It's a legacy class and has the same property as HashMap.
                    Only difference is it's safe to use in multithreaded environment means it's thread-safe.
                     It does not allow null key and null value.

LinkedHashMap : It is an ordered Map as it maintains insertion order while storing elements.
                             Elements can be retrieved as per insertion order.
                            It has faster iteration than other Maps.

TreeMap : It's a sorted Map. Sorting can be made as per need basis by implementing Comparable interface.

Code Example :
package com.fastlearned;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class MapExample {

 public void hashMapMethod() {
  System.out.println("Inside hashMapMethod()==");
  Map map = new HashMap();
  map.put("k1", new ValueObject("v3"));
  map.put("k2", new ValueObject("v4"));
  map.put("k3", new ValueObject("v6"));

  System.out.println("get the value of k1 = " + map.get("k1"));

  System.out.println("get all the keys " + map.keySet());
  // retrieving all the key and values
  for (Entry keyVal : map.entrySet()) {
   System.out.println(" key = " + keyVal.getKey() + " value = "
     + keyVal.getValue());
  }

 }

 public void hashTableMethod() {
  System.out.println("Inside hashTableMethod()==");
  Map map = new Hashtable();
  map.put("k1", new ValueObject("v3"));
  map.put("k2", new ValueObject("v4"));
  map.put("k3", new ValueObject("v6"));

  System.out.println("get the value of k1 = " + map.get("k1"));

  System.out.println("get all the keys " + map.keySet());
  // retrieving all the key and values
  for (Entry keyVal : map.entrySet()) {
   System.out.println(" key = " + keyVal.getKey() + " value = "
     + keyVal.getValue());
  }

 }

 public void linkedHashMapMethod() {
  System.out.println("Inside linkedHashMapMethod() == ");

  Map map = new LinkedHashMap();
  map.put("k1", new ValueObject("v3"));
  map.put("k2", new ValueObject("v4"));
  map.put("k3", new ValueObject("v6"));

  System.out.println("get the value of k1 = " + map.get("k1"));

  System.out.println("get all the keys " + map.keySet());
  // retrieving all the key and values in ordered form
  for (Entry keyVal : map.entrySet()) {
   System.out.println(" key = " + keyVal.getKey() + " value = "
     + keyVal.getValue());
  }

 }

 public void treeMapMethod() {

  System.out.println("== Inside treeMapMethod() == ");
  Map map = new TreeMap();
  map.put(100, new ValueObject("v3"));
  map.put(20, new ValueObject("v4"));
  map.put(34, new ValueObject("v6"));

  System.out.println("get the value of key 20 = " + map.get(20));

  System.out.println("get all the keys " + map.keySet());
  // retrieving all the key and values in ordered form
  for (Entry keyVal : map.entrySet()) {
   System.out.println(" key = " + keyVal.getKey() + " value = "
     + keyVal.getValue());
  }

 }

 /**
  * @param args
  */
 public static void main(String[] args) {

  MapExample m = new MapExample();
  m.hashMapMethod();
  m.hashTableMethod();
  m.linkedHashMapMethod();
  m.treeMapMethod();

 }

 class ValueObject {
  String value;

  public ValueObject(String val) {
   value = val;

  }

  @Override
  public String toString() {

   return value;
  }

 }
}

Output :
 Inside hashMapMethod()==
get the value of k1 = v3
get all the keys [k3, k1, k2]
 key = k3 value = v6
 key = k1 value = v3
 key = k2 value = v4
Inside hashTableMethod()==
get the value of k1 = v3
get all the keys [k3, k2, k1]
 key = k3 value = v6
 key = k2 value = v4
 key = k1 value = v3
Inside linkedHashMapMethod() == 
get the value of k1 = v3
get all the keys [k1, k2, k3]
 key = k1 value = v3
 key = k2 value = v4
 key = k3 value = v6
== Inside treeMapMethod() == 
get the value of key 20 = v4
get all the keys [20, 34, 100]
 key = 20 value = v4
 key = 34 value = v6
 key = 100 value = v3




Queue :  Queue maintains FIFO (First In First Out) order.
                Queue has some important methods as below

boolean offer(E element)

adds the given element to the tail of this deque and returns true, provided the queue
is not full. If the queue is full, the first method throws an IllegalStateException,
whereas the second method returns false

E poll()
removes and returns the element at the head of this queue, provided the queue is
not empty. If the queue is empty, the first method throws a NoSuchElementException,
whereas the second method returns null.

E peek()

returns the element at the head of this queue without removing it, provided the queue
is not empty. If the queue is empty, the first method throws a NoSuchElementException,
whereas the second method returns null.

Priority Queue :
                   A priority queue retrieves elements in sorted order after they were inserted in arbitrary
order. That is, whenever you call the remove method, you get the smallest element currently
in the priority queue. However, the priority queue does not sort all its elements. If
you iterate over the elements, they are not necessarily sorted. The priority queue makes
use of an elegant and efficient data structure, called a heap. A heap is a self-organizing
binary tree in which the add and remove operations cause the smallest element to gravitate
to the root, without wasting time on sorting all elements.

Code Example :

package com.fastlearned;

import java.util.PriorityQueue;
import java.util.Queue;

public class QueueExample {
 
 
 public void queueMethod()
 {
   Queue queue = new PriorityQueue();
   queue.offer("a");
   queue.offer("b");
   queue.offer("c");
   
   for(int i = 0;i< 3;i++)
   {
    System.out.println("queue head element "+queue.peek());
    System.out.println("queue removes head element "+queue.poll());
   }
   
   System.out.println("after pollimg 3 elements of the queue "+queue.size());
   
   
 }
 

 /**
  * @param args
  */
 public static void main(String[] args) {
  
  QueueExample qExample = new QueueExample();
  qExample.queueMethod();
 }

}

Output :
queue head element a
queue removes head element a
queue head element b
queue removes head element b
queue head element c
queue removes head element c
after pollimg 3 elements of the queue 0


Sorting a List using comparator

package com.fastlearned;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortingExample {

 private List userList;

 SortingExample() {
  userList = new ArrayList();
  userList.add(new User(10, 35, "Sukanta"));
  userList.add(new User(30, 23, "Ahmed"));
  userList.add(new User(8, 12, "Kajol"));

 }

 public void sortMethod() {
  System.out.println("== inside sortMethod() == ");
  // sorting of a hashSet

  Collections.sort(userList);
  for (int i = 0; i < userList.size(); i++) {
   System.out.println(i + "th index = " + userList.get(i));
  }

 }

 public void sortByNameMethod() {
  System.out.println("== inside sortByNameMethod() == ");
  // sorting of a hashSet
  Comparator nameComparator = new Comparator() {

   @Override
   public int compare(User o1, User o2) {

    return o1.name.compareTo(o2.name);
   }
  };
  Collections.sort(userList, nameComparator);
  for (int i = 0; i < userList.size(); i++) {
   System.out.println(i + "th index = " + userList.get(i));
  }

 }

 public void sortByRollNumberMethod() {
  System.out.println("== inside sortByRollNumberMethod() == ");
  // sorting of a hashSet
  Comparator nameComparator = new Comparator() {

   @Override
   public int compare(User o1, User o2) {

    return (o1.rollNumber - o2.rollNumber);
   }
  };
  Collections.sort(userList, nameComparator);
  for (int i = 0; i < userList.size(); i++) {
   System.out.println(i + "th index = " + userList.get(i));
  }

 }

 /**
  * @param args
  */
 public static void main(String[] args) {

  SortingExample example = new SortingExample();
  example.sortMethod();
  example.sortByNameMethod();
  example.sortByRollNumberMethod();
 }

 class User implements Comparable {
  int id;
  int rollNumber;
  String name;

  User(int _id, int _rollNumber, String _name) {
   id = _id;
   rollNumber = _rollNumber;
   name = _name;

  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + getOuterType().hashCode();
   result = prime * result + id;
   return result;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object obj) {
   if (this == obj)
    return true;
   if (obj == null)
    return false;
   if (getClass() != obj.getClass())
    return false;
   User other = (User) obj;
   if (!getOuterType().equals(other.getOuterType()))
    return false;
   if (id != other.id)
    return false;
   return true;
  }

  private SortingExample getOuterType() {
   return SortingExample.this;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
   return "User [id=" + id + ", rollNumber=" + rollNumber + ", name="
     + name + "]";
  }

  @Override
  public int compareTo(User o) {

   return (id - o.id);
  }

 }
}

Output :
== inside sortMethod() == 
0th index = User [id=8, rollNumber=12, name=Kajol]
1th index = User [id=10, rollNumber=35, name=Sukanta]
2th index = User [id=30, rollNumber=23, name=Ahmed]
== inside sortByNameMethod() == 
0th index = User [id=30, rollNumber=23, name=Ahmed]
1th index = User [id=8, rollNumber=12, name=Kajol]
2th index = User [id=10, rollNumber=35, name=Sukanta]
== inside sortByRollNumberMethod() == 
0th index = User [id=8, rollNumber=12, name=Kajol]
1th index = User [id=30, rollNumber=23, name=Ahmed]
2th index = User [id=10, rollNumber=35, name=Sukanta]


No comments:

Post a Comment