Thursday, August 19, 2010

Java Collection

Collection in Java

The interface and class hierarchy for collections

Key Interfaces of the Collections Framework are:

  Collection, List, Set, SortedSet ; Map, SortedMap


 Ordered:  When a collection is ordered, it means you can iterate through the collection in a specific (not-random) order. A Hashtable collection is not ordered. An ArrayList is however ordered based on the elements index position.  LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet.

Sorted: A sorted collection means a collection sorted by natural order. The natural order is defined by the class of the objects being sorted.


List

 List is an interface cares about the index. The one thing that List has that nonlists don't have is a set of methods related to the index like get(int index),  indexOf(),  add(int index, Object obj) etc.

ArrayList

It implements List,  gives fast iteration and fast random access. It is an ordered collection(by index), but not sorted.

Vector

Vector implements List, is basically same as ArrayList, but Vector methods are synchronized for thread safety.

LinkedList

LinkedList implements List,  is ordered by index position like ArrayList, except that the elements are doubly linked to one another. This linkage gives you new methods for adding or removing from the beginning or end, which makes an easy choice for implementing a stack or queue. It iterates more slowly than ArrayList, but a good choice for fast insertion or deletion.

Set

Set is an interface which cares for uniqueness - it does not allow duplicates.

HashSet

HashSet implements Set, is unsorted, unordered Set. It uses the hashcode of the object being inserted, so the more efficient your hashCode() implementation the better access performance you'll get. 

LinkedHashSet

LinkedHashSet implements Set, is an ordered version of HashSet that maintains a doubly linked list accross all elements.  Use this class instead of HashSet where you care of the iteration order.

TreeSet

TreeSet implements SortedSet interface, is one of two sorted collections(other is TreeMap), guarantees that the elements will be in ascending order, according to the natural order of the elements. 

Map

Map cares about unique identifiers. You map a unique ID to a specific value, where key/value pair are both objects.


Map map = new HashMap();

or

Map<String, Integer> map = new HashMap<String, Integer>();
    map = new TreeMap();

    map.put("a"new Integer(1));
    map.put("b"new Integer(2));
    map.put("c"new Integer(3));

for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
      Map.Entry entry = (Map.Entryit.next();
      Object key = entry.getKey();
      Object value = entry.getValue();
    }

HashMap

The HashMap gives you an unsorted, unordered Map. HashMap allows one null key in a collection and multiple null values in a collection.

Hashtable

Like Vector, Hashtable has been from prehistoric Java times.  Hashtable is the synchronized counterpart of HashMap. Hashtable does not allow nulls, neither as a key nor as a value.

LinkedHashMap

Like Set's counterpart LinkedHashSet, the LinkedHashMap collection maintains the insertion order. Although it is slower than HashMap for adding and removing elements,  but you can expect faster iteration with LinkedHashMap.

TreeMap

TreeMap is a sorted Map.  TreeMap lets you pass you own comparison rules


1. Use Vector if there are multiple threads and ArrayList if there is only a single thread.
2. Use Hashtable if there are multiple threads and HashMap if there is only a single thread.
3. Use StringBuffer if there are multiple threads and StringBuilder if there is only a single thread.

Eg: Prefer using,
List list = new Vector()
or
List list = Collections.synchronizedList(new ArrayList);

instead of
Vector list = new Vector();

The first two allows the code to be more flexible.

import java.util.ArrayList;

import java.util.Collection;

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.LinkedHashSet;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.SortedMap;

import java.util.SortedSet;

import java.util.TreeMap;

import java.util.TreeSet;


public class CollectionAll {

  public static void main(String[] args) {

    List list1 = new LinkedList();

    list1.add("list");

    list1.add("dup");

    list1.add("x");

    list1.add("dup");

    traverse(list1)

    List list2 = new ArrayList();

    list2.add("list");

    list2.add("dup");

    list2.add("x");

    list2.add("dup");

    traverse(list2)

    Set set1 = new HashSet();

    set1.add("set");

    set1.add("dup");

    set1.add("x");

    set1.add("dup");

    traverse(set1)

    SortedSet set2 = new TreeSet();

    set2.add("set");

    set2.add("dup");

    set2.add("x");

    set2.add("dup");

    traverse(set2)

    LinkedHashSet set3 = new LinkedHashSet();

    set3.add("set");

    set3.add("dup");

    set3.add("x");

    set3.add("dup");

    traverse(set3)

    Map m1 = new HashMap();

    m1.put("map""Java2s");

    m1.put("dup""Kava2s");

    m1.put("x""Mava2s");

    m1.put("dup""Lava2s");

    traverse(m1.keySet())

    traverse(m1.values())

    SortedMap m2 = new TreeMap();

    m2.put("map""Java2s");

    m2.put("dup""Kava2s");

    m2.put("x""Mava2s");

    m2.put("dup""Lava2s");

    traverse(m2.keySet())

    traverse(m2.values())

    LinkedHashMap /* from String to String */m3 = new LinkedHashMap();

    m3.put("map""Java2s");

    m3.put("dup""Kava2s");

    m3.put("x""Mava2s");

    m3.put("dup""Lava2s");

    traverse(m3.keySet())

    traverse(m3.values())

  }


  static void traverse(Collection coll) {

    Iterator iter = coll.iterator();

    while (iter.hasNext()) {

      String elem = (Stringiter.next();

      System.out.print(elem + " ");

    }

    System.out.println();

  }


}


//            ListIterator ref = reference.listIterator();
//            int i=0;
//            while (ref.hasNext()){
//                System.out.println(i+"-"+ref.next());                
//                i++;
//                SomNode iter = (SomNode) ref.next();
//                
//            }
//            
            
//            Iterator<SomNode> iter = reference.iterator();
//            while (iter.hasNext()) {
//                for (int j = 0; j < iter.next().getValues().length; j++) {
//                    System.out.println(j+"+"+iter.next().getValues()[j] + ",");
//                }
//                System.out.println();
//            }



How to merge two Array List containing Objects   
public class MyObject {

private String name;
private int age;

public MyObject() {
}

public MyObject(String name, int age) {
this.name = name;
this.age = age;
}

//setter and getter for name & age


public boolean equals(Object obj) {
if(obj == null) {
return false;
}
if( !(obj instanceof MyObject)) {
return false;
}
MyObject newObject = (MyObject) obj;
return this.name.equals(newObject.name);
}

}


Test Code:

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

public abstract class TestMyObject {

/
@param args
loganathank
void

*/
public static void main(String[] args) {
MyObject obj1 = new MyObject("obj1",1);
MyObject obj2 = new MyObject("obj2",1);
MyObject obj3 = new MyObject("obj3",1);
MyObject obj4 = new MyObject("obj4",1);

List L1 = new ArrayList();
L1.add(obj1);
L1.add(obj2);
L1.add(obj3);

List L2 = new ArrayList();
L2.add(obj4);
L2.add(obj2);
L2.add(obj3);

Iterator l2Iterator = L2.iterator();
while(l2Iterator.hasNext()) {
Object obj = l2Iterator.next();
if(!L1.contains(obj)) {
L1.add(obj);
}
}
System.out.println(" L1.size " + L1.size());
}


}

0 comments:

Post a Comment