Search This Blog

Thursday, August 30, 2007

Java Collections

package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
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.Vector;
public final class Test {
/**
* @param args
*/
public static void main(String[] args) {
String string = null;
// collections List - Ordered,duplicate value permitted,null value
// allowed
List list = new ArrayList();
list.add("venky");
list.add("2ntuit");
list.add("3ntuit");
list.add(string);
list.add(null);
Iterator it = list.iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println("list " + str);
}
// Set - not ordered, duplicate value not permitted,null value allowed
Set set = new HashSet();
//Set set = new LinkedHashSet();//Same as HashSet but Insertion-Ordered
set.add("venky");
set.add("venky");
set.add("2ntuit");
set.add("1ntuit");
set.add("7ntuit");
set.add(string);
it = set.iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println("Set " + str);
}
// HashMap - key/Value pair, not ordered,duplicate key not allowed
// null key and null value allowed
Map map = new HashMap();
//Map map = new LinkedHashMap();//Same as HashMap but Insertion-Ordered
map.put("3", "bus");
map.put("1", "Venky");
map.put("2", string);
map.put(null, null);
System.out.println(map.size());
it = map.keySet().iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println("Map " + str);
}
// Hashtable - key/Value pair,Not ordered,Null key/null value not
// allowed,Duplicate Key not allowed
Map table = new Hashtable();
table.put("3", "bus");
table.put("de2", "Venky");
table.put("1", "Venky");
table.put("xy", "Venky");
table.put("1tz", "Venky");
// table.put(string, ""); // throws NullPointerException
System.out.println(table.size());
it = table.keySet().iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println("table " + str);
}
// Vector - Ordered,Duplicate value allowed,Null value allowed
List vector = new Vector();
vector.add("3ntuit");
vector.add("venky");
vector.add("2ntuit");
vector.add("2ntuit");
vector.add(string);
vector.add(null);
it = vector.iterator();
while (it.hasNext()) {
String str = (String) it.next();
System.out.println("vector " + str);
}
// Implementing a Queue
LinkedList queue = new LinkedList();
queue.add("venky");
queue.add("ctsenky");
System.out.println("queue " + queue);
// Get head of queue
Object o = queue.removeFirst();
System.out.println("queue " + queue);
}
public int getData(int userId) {
userId += 1;
return userId;
}
public static long factorial(long n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
}