Showing posts with label Collections(java.util). Show all posts
Showing posts with label Collections(java.util). Show all posts

Wednesday, April 1, 2009

Collection-Interface

The 1.2 release of the Java platform includes a new collections framework. A collection is an object that represents a group of objects. A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. The Collection interface is the root of the collection hierarchy. A Collection represents a group of objects, known as its elements. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. The JDK doesn't provide any direct implementations of this interface: It provides implementations of more specific subinterfaces like Set and List. This interface is the least common denominator that all collections implement.

Collection is used to pass collections around and manipulate them when maximum generality is desired.Collection frame work define a set classes and interfaces which can be used for representing a group of objects as single entity.In the case of c++ the corresponding collection frame work is known as STL(Standered template library) and collection is known as container.


There are six collection interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections. However, these interfaces contain collection-view operations, which allow them to be manipulated as collections.



Collection Interface:
It defines general methods ,which can be used for a group of individual objects.i.e a collection represents a group of individual ibjects.
Note:
Collection is an interface to represent a group of individual objects where as collections is an utility class for defining utility methods like sorting,searching… etc.
Collection Interface Methods:
This Interface defines general methods which can be applied on any collection object.
1.boolean add(Object obj)
2.boolean addAll(collection c)
3.boolean remove(Object o)
4.boolean removeAll(Collection c)
5.void clear()
6.boolean retainAll(Collection c)
removes all the elements in the collection except those present in c.
7.boolean contains(Object o)
8.boolean containsAll(Collection c)
9.boolean isEmpty()
10.int size()
returns the number of objects present in the collection
11.Object[] toArray()
mainly for improving the performance of the system.
12. Iterator iterator()
to return the objects one by one.


The primary advantages of a collections framework are that it:
• Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself.
• Increases performance by providing high-performance implementations of useful data structures and algorithms. Because the various implementations of each interface are interchangeable, programs can be easily tuned by switching implementations.
• Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
• Reduces the effort required to learn APIs by eliminating the need to learn multiple ad hoc collection APIs.
• Reduces the effort required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.
• Fosters software reuse by providing a standard interface for collections and algorithms to manipulate them.





SortedMap-TreeMap-Properties

SortedMap:
It is interface.If you want to store the elements based on some sorting order of keys we should go for the SortedMap.A SortedMap is a Map that maintains its mappings in ascending key order. It is the Map analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and telephone directories.

SortedMap Methods:
1) Object firstKey() //Returns the firstkey of the sortedset
2) Object lasKey() // Returns the last key of the sortedset
3) SortedMap headMap( Object key) //Returns the SortedMap whose keys are smaller than or equal to specified key
4) SortedMap tailMap( Object key) // Returns the SortedMap whose keys are greater than or equal to specified key
5) SortedMap subMap( Object key1,Object key2) // Returns a SortedMap whose keys are greater than or equal to the key1 but less than key2
6) Comparator comparator(): //Returns Comparator Object that defines the underlying sorting technique.If the natural sorting order is used then returns null

TreeMap:

  • It implements the SortedMap interface.
  • The underlying datastructure for the TreeMap is Red-Black Tree
  • Insertion order is not preserved
  • Duplicate keys are not allowed but values may be duplicated
  • Heterogeneous objects are not allowed for the keys but values may be heterogeneous.
  • As first entry null key insertion is possible to the empty treemap but after if you try to add any other entry we will get the NullPointerException
  • If you are trying to add an entry with the null key to an already exsting treemap we will get the NullPointerException
  • There are no restriction for null values
  • If natural sorting order is used then the keys must be comparable otherwise classCastException
TreeMap Constructors:
TreeMap map=new TreeMap():
TreeMap map=new TreeMap(Comparatror c):
TreeMap map=new TreeMap(Map m):
TreeMap map=new TreeMap(SortedMap m):

TreeMap Demo program:
package myutil;

import java.util.TreeMap;

public class TreeMapEx1 {
public static void main(String[] args)
{
TreeMap map=new TreeMap();
map.put(new Integer(100),"orange");
map.put(new Integer(200) ,"apple");
map.put(new Integer(300),"grapes");
System.out.println("The TreeeMap Is "+map);
// Try to place the null you will get NullPointerException
// map.put(null,"javasun");
}
}

output:
The TreeeMap Is {100=orange, 200=apple, 300=grapes}

TreeMap Example code with Comparator:
package myutil;

import java.util.Comparator;
import java.util.TreeMap;
class Mycompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return -i1.compareTo(i2);
}
}

public class TreeMapCom {
public static void main(String[] args)
{
TreeMap map=new TreeMap(new Mycompare());
map.put(new Integer(100),"orange");
map.put(new Integer(300),"apple");
map.put(new Integer(200),"grapes");
map.put(new Integer(400),"grapes");
System.out.println("The TreeeMap Is "+map);
// Try to place the null you will get NullPointerException
//map.put(null,"javasun");
}
}

output:
The TreeeMap Is {400=grapes, 300=apple, 200=grapes, 100=orange}


Properties:
  • It is the child class of Hashtable
  • For Properties both keys and values must be Strings
Propertes Constructors:
Properties props=new Properties();

Methods:
getProperty(String key);
setProperty(String key,String value);
propertyNames();
load(InputStream stream);
store(OutputStream stream,String comment);

Properties Demo Program:
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args ){
Properties props=new Properties();
FileInputStream fis=new FileInputStream(“abc.properties”);
props.load(fis);//Load the file
System.out.println(props.getProperty(“orange”));
props.setProperty(“apple’,200);
FileOutputStream fos=new FileOutputStream(“abc.properties”));
}
}



Map-Hashtable-HashMap-WeakHashMap-IdentityHashMap

MAP Interface:A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value.

  • Map is not the child interface of Collection interface
  • If you want to store the values or objects as key value pairs we go for the the Map interface
  • Both key and values are objects
  • Duplication of keys is not allowed but values may be duplicated
  • Key –Value Pair is called an Entry



Methods in Map Interface:

1)Object put(Object key,Object value) //Inserts a value into the map.if the key is already exists it will replace the old values with new one
2)Object get(Object key) // Returns the value associated with the key otherwise returns null
3)Object remove(Object key) // It removes the entry associated with the key and returns the corresponding value otherwise returns null
4)boolean containsKey(Object key)
5)boolean containsValue(Object key)
6)int size()
7)boolean isEmpty()
8)void clean()
9)void putAll(Map m)
10)Set keySet()
11)Collection values()
12)Set emptySet()
// The following three methods collection view of Map
13)Object getKey();
14)Object getValue();
15)Object setValue(Object obj)
//Entry is an inner interface present inside the map.It contains
the following three methods which can be applied on the entry object.
16)Object getKey();
17)Object getValue();
18)Object setValue(Object obj)

Note:
interface Map{
Interface Entry{ // inner interface entry
Object getKey();
Object getValue();
Object setValue(Object obj)
}
}

Hashtable:
  • The underlying datastructure for the HashTable is the Hastable itself.
  • Heterogeneous values are allowed for both keys and values
  • null insertion is allowed for both keys and values for the first element violation leads to NullPointerException
  • Almost all methods or Hashtable are synchronized hence it is thread safe
  • Insertion order is not preserved and the objects are arranged based on hashcode
  • Duplicate objects for values but keys are not to be duplicated
Hashtable Constructors:
Hashtable table=new Hashtable();
Hashtable table=new Hashtable(int initialCapacity);
Hashtable table=new Hashtable(int initialCapacity,float fillRatio);
Hashtable table=new Hashtable(Map m);

Hashtable Demo:
import java.util.Hashtable;

public class HashtableEx1 {
public static void main(String[] args) {
Hashtable table=new Hashtable();
table.put(new Integer(1),"xxx");
table.put(new Integer(24),"yyy");
table.put(new Integer(3),"zzz");
table.put(new Integer(8),"aaa");
table.put(new Integer(9),"bbb");
table.put(new Integer(2),"sss");
System.out.println("The Hashtable is "+table);
}
}

output:
The Hashtable is {9=bbb, 8=aaa, 3=zzz, 2=sss, 24=yyy, 1=xxx}


HashMap:
  • The underlying datastructure for HashMap is Hashtable
  • Duplicate keys are not allowed but values may be duplicated
  • Insertion order is not preserved
  • Heterogeneous key and values are allowed
  • Null key is allowed only once but values are nulls for any number of times
HashMap Constructors:
1) HashMap map=new HashMap();
it Create the empty hashmap with the default initial capacity 16 and fillRatio 0.75
2) HashMap map=new HashMap(int initialCapacity);
it Create a HashMap with the specified nitialCapacity and default load factor
3) HashMap map=new HashMap(int nitialCapacity,float loadFactor);
4) HashMap map=new HashMap(Map m);

HashMapDemo Program:
import java.util.*;
public class HashMapEx1 {
public static void main(String... args) {
HashMap map=new HashMap();
map.put("orange",new Integer(1000));
map.put("apple",new Integer(2000));
map.put("banana",new Integer(3000));
map.put("grapes",new Integer(4000));
System.out.println("The Map "+map);
System.out.println(map.put(("orange"),new Integer(1001)));
System.out.println("map "+map);
Set s=map.keySet();
System.out.println("The Key Set"+s);
Collection values=map.values();
System.out.println("The Values Are "+values);
Set s1=map.entrySet();
System.out.println("The Entry Set"+s1);
}
}


output:
The Map {orange=1000, grapes=4000, apple=2000, banana=3000}
1000
map {orange=1001, grapes=4000, apple=2000, banana=3000}
The Key Set[orange, grapes, apple, banana]
The Values Are [1001, 4000, 2000, 3000]
The Entry Set[orange=1001, grapes=4000, apple=2000, banana=3000]

LinkedHashMap:
It is exactly similar to the HashMap except the following differences
HashMap:
  • Underlying datastructure is Hashtable
  • Insertion order is not preserved
  • While iterating we can not give guarantee for processing order. Hence we can not use it for caching
LinedHashMap:
  • Underlying datastructures are hashtable and doubly linkedlist
  • Insertion order of elements is preserved
  • While iterating elements we can give guarantee for processing order.Hence we can use for caching
IdentityHashMap:
In case of HashMap JVM uses the equals() method to identify the duplicate keys
But if want to use the == operator to identify the duplicates we go for the IdentityHashMap
Incase of IdentityHashMap two key reference i1 and i2 are equal if and only if bot i1 and i2 are pointing to the same object on the heap

IdentityHashMap Demo Program:
import java.util.IdentityHashMap;

public class IdentityHashMapEx1 {
public static void main(String... args) {
IdentityHashMap map=new IdentityHashMap ();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
map.put(i1,"orange");
map.put(i2,"apple");
System.out.println("The Map"+map);
}
}


WeakHashMap:
  • WeakHashMap is not a child class of HashMap
  • HashMap dominates the garbage collector.if any objects are associated with the HashMap eventhough that object does not have any external references .Garbage collector is not allowed to destroy that object
  • But garbage collector dominate the WeakHashMap that is in case of hashmap if the key is not reachable garbage collector is allowed to destroy whole entry associated with the key
WeakHashMap Demo Program:
import java.util.WeakHashMap;
class Temp {
public void finalize() {
System.out.println("finalize() Called");
}
public String toString() {
return "Temp";
}
}
public class WeakHashMapEx1 {
public static void main(String[] args) {
WeakHashMap map=new WeakHashMap();
Temp t=new Temp();
map.put(t,"orange");
t=null;
System.gc();
System.out.println("The Map"+map);
}
}

output:
finalize() Called
The Map{}

Collection-List-Vector-ArrayList-Stack-LinkedList

Collection Interface :
The Collection interface is the root of the collection hierarchy. A Collection represents a group of objects, known as its elements. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. The JDK doesn't provide any direct implementations of this interface: It provides implementations of more specific subinterfaces like Set and List. This interface is the least common denominator that all collections implement. Collection is used to pass collections around and manipulate them when maximum generality is desired.

It defines general methods ,which can be used for a group of individual objects.i.e a collection represents a group of individual ibjects.
Note: Collection is an interface to represent a group of individual objects where as collections is an utility class for defining utility methods like sorting,searching… etc.

List Interface:



  • It represents a group of individual objects where
  • Insertion order is preserved via indexes
  • Duplicate objects are allowed. .we can differentiate duplicate objects by using indexes.
  • A list is also known as sequence ArrayList ,LinkedList ,Vector and Stack implement List interface.
Following are the methods list interface :
1.boolean add(Object obj)
2.boolean add(int index,Object o)
3.boolean addAll(Collection c)
4.boolean addAll(int index,Collection c)
5.boolean remove(object o)
remove the first occurrence of this object
6.boolean removeAll(Collection c)
7.int indexOf(Object o)
return the index of first occurrence
returns -1 if there is no such object
8.int lastIndexOf(Objetc o)
9.Object get(int index)
there is no get method in the collection interface
10.Object set(int index , Object o)
11.ListIterator listIterator()
12.Object remove(int index)


Vector class:
  • The underlying datastructure for vector is growable array or resizable array.
  • Insertion order is preserved.
  • Null insertion is possible.
  • Duplicate objects are allowed.
  • Hetrogeneous objects are allowed.
  • It implemented RandomAccess,Clonable and Serializable interfaces.
  • Best choice for retrieval operation.
  • Worst choice for insertion or deletion in the middle.
When compare with ArrayList,Vector is preferable when thread safety is reqired because all the vector class methods are synchronized.

Vector methods:
For adding objects
1.add(Object o) ----> from collection
2.add(int index, Object o) ---------> from list
addElement(Object o) ---------> Vector
for removing objects
1.remove(Object o) ---------> from collection
2.remove(int index) -----------> from list
3.removeElement(Object o) ----------> Vector.
4.removeElementat(int index) -------------> Vector
5.removeAllElements()
6.clear() ------------> from collection
For accessing objects.
1.Object get(int index)
2.Object elementAt(int index)
3.Object firstElement()
4.Object lastElement();
5.int size()
6.int capacity();

Constructors of Vector:
1.Vector v=new Vector()
create an empty Vector with default initial capacity 10.
If the Vector reaches its maximum capacity a new Vector object will create with a capacity = current capacity * 2 i.e doubles.
2.Vector v=new Vector(int initialcapacity)
Constructs an empty vector with the specified capacity.
3.Vector v=new Vector(Collection c)
4.Vector v=new Vector(int initialcapacity,int incrementalcapacity)

Vector Example:
import java.util.*;
class VectorDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement(“a”);
for(int i=0;i<10;i++)
{
v.addElement(new Integer(i));
}
System.out.println(v);
System.out.println(v.capacity()); // 10
v.add(“b”);
System.out.println(v.capacity()); // 20
}
}

Array List:
  • The underlying datastructure for array List is growable array or resizable array.
  • Insertion order is preserved.
  • Duplicate objects are allowed.
  • Hetrogeneous objects are allowed.
  • Null insertion is possible any number of times.
Constructors of ArrayList:
1.ArrayList a=new ArrayListA();
creates an empty arraylist with the default initial capacity 10.
If arraylist reaches its maximum capacity ,it creates a new arraylist object with the new capacity as (Current capacity * 3/2 ) + 1;
2.arrayList a=new ArrayList(int initialcapacity)
creates an empty arraylist with the specified initial capacity.
3.ArrayList a=new ArrayList(Collection c)
Construct an equivalent arraylist for the given collection object.

ArrayList Example:
import java.util.*;
class ArraylistDemo
{
public static void main(String arg[])
{
ArrayList a=new ArrayList();
a.add(“aaa”);
a.add(“bbb”);
a.add(“new Integer(10)”);
a.add(null);
a.add(1,”ccc”);
System.out.println(a); // [aaa, ccc,bbb,10,null]
}
}
every collection class implemented clonable and serializable interfaces.
System.out.println(a instanceOf java.io.Serializable); // true
System.out.println(a instanceOf java.io.Clonable); // true

  • ArrayList and Vector classes implemented Random Access interface.Any element in ArrayList and Vector we can access with same speed.Hence ArrayList is best suitable for retrivel operation.
  • ArrayList is a non-synchronised one introduced in 1.2 version.It is a non-legacy class which has high performance.But we can’t achieve security.Where as vector is a synchronized in 1.0 version .It is a legacy class which has low performance But we can achive security.
  • In ArrayList ,there is a possibility for data corruption as it is thread safe.ArrayList is the worrest choice,If your frequent operation is insertion or deletion in the middle,because it reqires so many internal shift operations .
LinkedList:
  • The underlying data structure for LinkedList is DoublyLinkedList.
  • Insersion order is preserved.
  • Duplicate objects are allowed.
  • Null insertion is possible any number of times.
  • Hetrogeneous objects are also allowed.
  • It implemented serializable and clonable interfaces but not RandomAccess interface.
  • LinkedList is the best choice if your frequent operation is insertion or deletion in the middle.
  • LinkedList the worest choice if your frequent operation retrieval operation.
LinkedList class contain the following methods for implementing Stacks and Queues.
1.void addFirst(Object o)
2.void addLast(Object o)
3.Object removeFirst()
4.Object removeLast()
5.Object getFirst()
6.Object getLast()

Constructors of LinkedList:
1.LinkedList l=new LinkedList();
create an empty LinkedList (initial capacity is not applicable) size != capacity
2.LinkedList l=new LinkedList(Collection c)

LinkedList Example
import java.util.*;
class LinkedListDemo
{
public static void main(String arg[])
{
LinkedList l=new LinkedList();
l.add(“laxman”);
l.add(new Integer(10));
l.add(null);
l.add(“laxman”);
l.add(0,”scjp”);
l.add(“gorantla”);
l.removeLast();
l.addFirst(“ccc”);
System.out.println(l); // [ccc,gorantla,scjp,10,null]
}
}


Stack Class:
It is the child class of Vector
Contain only one constructor
Stack s=new Stack();
Methods of stack class:
1.Object push (Object obj)
It pushes an element into stack and that element also return.
2.Object pop()
removes the top of the stack and the object is returned.
3.Object peek()
returns the element present on the top of the stack.
4.boolean empty()
returns true if the stack isempty otherwise false.
5.int search(Object o)
returns the offset from the top of the stack if the Object present else return -1.
Ex: s.search(“a”);
Stack example:
Import java.util.*;
Class StackDemo
{
public static void main(String arg[])
{
Stack s=new Stack();
s.push(“a”);
s.push(“b”);
s.push(“c”);
System.out.println(s); // [a,b,c]
System.out.println(s.search(“c”)); // 1
System.out.println(s.search(“a”)); // 3
}
}
insertion order should be preserved should be not LIFO.



treeset-Comparator

SortedSet Interface:
If you want to represent a group of individual,unique set of objects ,where all the objects are in some sorting order (either natural sorting order or customized sorting order) then we should go for SortedSet.
SortedSet methods:
1.Object first()
returns the first element in sortedset
2.Object last()
return the last element in sortedset.
3.SortedSet headset(Object end)
returns the sorted set containing the elements which are lessthan end.
4.SortedSet tailSet(Object begain)
returns the sorted set that includes the elements which are greaaer than or equal to begain.
5.SortedSet subset(Object begain,Object End)
return a sortedset that includes the elements which are greater than or equal to begain but less than end.
6.Comparator comparator()
decribes underlying sorting technique if default sorting technique is used then it simply returns null.

TreeSet class :

  • The underlying datastructure for the treeset is balancedtree.
  • Duplicate objects are not allowed.
  • Insertion order is not preserved ,but all the elements are arranged in some sorting order.
  • Null insersion is possible but only one.
  • Hetrogeous objects are not allowed ,voialtion leads to runtime exception saying classcast exception.
Constructors:
1.treeSet t=new TreeSet()
creates an empty TreeSet where the sorting technique is default natural order.
2.TreeSet t=new TreeSet(Comparator c)
creates an empty TreeSet ,where the sorting technique is specified by comparator object .( this is for customized sorting).
3.TreeSet t=new TreeSet(Collection c)
4.TreeSet t=new TreeSet(SortedSet s)
reserved for future purpose.

TreeSet Example:
import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet();
t.add(“z”);
t.add(“k”);
t.add(“b”);
t.add(“f”);
System.out.println(t); // [b,f,k,z]
t.add(new Integer(10)); // class cast exception
}
}
In case of integers (10,15,20) it followes ascending order.
TreeSet t=new TreeSet()
t.add(null);
System.out.println(t);
t.add(“a”);
System.out.println(t); // nullpointer exception
Null acceptance:
For the empty TreeSet as the first element we are allowed to add null.
But after adding null if we are trying to add anyother ,we will get a RTE saying NullPointerException”.If the treeset already contains some elements,If we are trying to add null causes once again nullpointer Exception.

In case of StringBuffer objects
t.add(new StringBuffer(‘a”));
t.add(new StringBuffer(“b”));
t.add(new StringBuffer(‘c”));
t.add(new StringBuffer(“l”));
System.out.println(t); // RTE saying classcast exception

i.e In the treeset we should add only.
  • Homogeneous and comparable objects violation leads classcast Exception
  • An object is said to be comparable if an only if the corresponding class implements comparable interface.
  • String and Wrapper classes already implemented comparable interface.But StringBuffer doesn’t implemented comparable interface.
Comparator Interface:
If you want to define our own sorting we havwet to implement comparator interface.
This interface present in java.util package.
This interface contain the following two methods.
1.public int compare(Object o1,Object o2)
return –ve number if o1 comes before o2.
return +ve number If o1 comes after o2.
returns zero if o1 and o2 equal.
2.public Boolean equals(Object o)
by using comparator interface we can define our own customized sorting.

Write a program to insert integer object in the TreeSet where the Sorting technique is descending order.

import java.util.*;
class TreeSetDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new MyComparator());
t.add(new Integer(20));
t.add(new Integer(10));
t.add(new Integer(30));
t.add(new Integer(100));
System.out.println(t); // 10 ,20 ,30,100
}
}
class MyComparator implements Comparator
{
public int Compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
int i1=i1.intValue();
int i2=i2.intValue();
if(i1>i2)
return -1;
else
if(i1 > i2)
return +1;
else
return 0;
}
}

write a program to insert string objects into the TreeSet where the sorting order is increasing order of String lengths.

import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new Mycomparator())
t.add(“aaaaaa”);
t.add(“bbbb”);
t.add(“ccc”);
System.out.println(t); // [ccc,bbbb,aaaaaa]
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
if(s1.length() < s2. length())
return -1;
else
if(s1.length() > s2.length())
return +1;
else
return 0;
}
}

program to insert StringBuffer Objects in the treeSet according to dictionary order

import java.util.*;
class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer(“aaa”);
t.add(new StringBuffer(“bbb”);
t.add(new StringBuffer(“ccc”);
t.add(new StringBuffer(‘ddd”);
System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s1.compareTo(s2);
//return s2.compareTo(s1);
}
}

if we return always like this:
return 0; // aaa
return +100 // bbb,ccc,aaa,ddd
return -100 // ddd,aaa,ccc,bbb



collection-set-HashSet-LinkedHashSet

Collection Interface:
The Collection interface is the root of the collection hierarchy. A Collection represents a group of objects, known as its elements. Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. The JDK doesn't provide any direct implementations of this interface: It provides implementations of more specific subinterfaces like Set and List. This interface is the least common denominator that all collections implement. Collection is used to pass collections around and manipulate them when maximum generality is desired.

It defines general methods ,which can be used for a group of individual objects.i.e a collection represents a group of individual ibjects.
Note:
Collection is an interface to represent a group of individual objects where as collections is an utility class for defining utility methods like sorting,searching… etc.

Set Interface:
A Set is a collection that cannot contain duplicate elements. As you might expect, this interface models the mathematical set abstraction. It is used to represent sets like the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine.


This interface doesn’t contain any new methods.we have to use collection interface methods.

Hash Set:

  • The underlying data structure for the set is Hashtable.
  • Elements are inserted based on the hash code,hence insertion order is not possible.
  • If we are trying to add a duplicate object no chance of getting RTE or CTE add() just simply returns false.
  • Hetrogeneous objects are allowed.
  • Null insertion is possible but only once.
  • HashSet is the best choice for searching operations.
  • Hashset implemented serializable and clonable interface.
Constructors:
1.HashSet h=new HashSet();
Creates a new empty HashSet with default initial capacity 16 and load factor or fill ratio 0.75.
2.HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet with specified initial capacity and default fill ratio is 0.75.
3.HashSet h=new HashSet(int int itialcapacity,float fillratio)
creates an empty HashSet with the specified initial capacity and specified fill ratio.
4.HashSet h=new HashSet(Collection c)

HashSet Example:
import java.util.*;
class HashSetDemo
{
public static void main(String arg[])
{
HashSet h=new HashSet();
System.out.println(h.add(“b”); // true
h.add(“b”);
h.add(“c”);
h.add(“d”);
h.add(null);
h.add(new Integer(10));
System.out.println(h.add(“d”); // flase
System.out.println(h); // depends on hash code number insertion order.
}
}

Linked Hash Set:
The linked hash set is exactly similar to HashSet Except the following differences.
  • Hashtable is the underlying data structure of hashset.Hashtable and doubly linkedlist are the underlying datastructures for linkedhashset.
In the above demo LinkedHashSet l=new LinkedHashSet();
Then the output: [b,c,d,null,10] preceding with true and flase.i.e insertion order is preserved.
We can use LinkedHashSet for implementing caching memory.




Sunday, February 15, 2009

Comparable Interface and clonable interface

Comparable Interface:
This is present in java.lang.package
Contains the following one method.
1.public int compareTo(Object o)
if returns –ve integer if o1 has to place before o2.
If returns +ve integer if o1 has to to place after o2.
If returns zero then o1 and o2 are equal.
All the wrapper classes and string class already implemented comparable interface. But the StringBuffer doesn’t implement comparable interface.
Comparable Interface Example:
Interface comparable
{
public int compareTo(Object o)
{
TreeSet t=new TreeSet(0;
t.add(“a”);
t.add(‘z”);
System.out.println(t); // a,z (:: z.compareTo(“a”);)
System.out.println((“a”).compareTo(“z”)); //-25
System.out.println((new Integer(10).compareTo(new Intege(1)); // +1
}
}|
Marker or Tag Interface:
If an interface is marked for some ability such type of interfaces are called Marker interfaces.
Ex: clonable,serializable
If an interface with out any method obviously accept ass marker interface.
Eventhough interface contains some methods,still we can consider as marker interface .If it is marked for some ability.
Ex:Comparable interface.
Intreger i1=new Integer(10);
Integer i2=new Integer(20);
System.out.println(i2.compareTo i1); // -1
System.out.println(i1.compareTo i2); // +1
System.out.println(i1.compareTo i1); // 0
System.out.println(i1.compareTo(“a”)); // CTE nullpointer exception


Cloneable interface:
Uptaining exact copy of a plant ,a bird,an animal or a human being is called cloning.
Cloning in programming uptaining bit wist exact copy of an object is called cloning.
cloning Example:

Class sample() implements cloneable
{
Int i=10;
Public static void main(string args[])throwsClone notSupportedEexception
{
Sample s1=new sample();
Sample s2=s1;
Sample s3=(sample)s1.clone();
S1.i=1000;
System.out.println(s3.i);
System.out.println(s1==s3);
we should type cast otherwise
CTE:in compatable types
Found: Object reqired=sample
The class must implements cloneable interface otherwise at runtime clone() results cloneNotsupportException
Example:
Class sample implements clonable
{
Int i=10;
Public static void main(string[]args)throws cloneNot support Exception
{
Object o=new object();
Object o2=o.clone();
}
CTE:clone() has protected access in java.lang.object
The protected numbers we can access, from with in the same package or from outside package but from outside package,the protected number can be accessed b using child class reference only.ie we can’t use parentclass reference to access protected number from outside package,validation leadsto CTE.

clone() method:
Protected object clone() throws clone not supported exception.
This method can used to prouduced exactly duplicate copy of an object..
All the objects can’t produce cloned object ,only clonable objects can produce duplicate copies .
An object is said to be conable if and only if the corresponding class implements clonable interface.
By using the folling object class clone() method we can produced cloned objects
Protected object clone() throws clone supported exception
CheckedException so we should handle by using try catch or throws to the caller by using throws clause.

Shallow cloning Example:
Class Student implements cloneable
{
String name;
String age;
Student(String name,String age)
{
This.name;
This.age=age;
]
Public Object clone()throws cloneNotSupportedException
{
Return this;
}
}
Class Student cloneDemo
{
Student s1= new Student(“hai”,”22”);
Student s2= (Student)s1.clone();
S2.name=”abc”;
System.out.println(s1.name);
Public static void main (String ar[])
{
StudentCloneDemo s1= new Student cloneDemo();
}
}
Deep cloning example:
Class Student implements cloneable
{
String name;
String age;
}
Student(String name ,String age)
{
This.name=name;
This.age=age;
}

Public Object clone(0throws CloneNotSuport Exception
{
try
{
ByteArrayOutputStream bas=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bas);
Oos.writeObject(this);
ByteArrayInputStream bias=new ByteArrayInputStream(bas.toByteArray());
ObjectInputStream oos=new ObjectInputStream(bias);
Return ois.readObject();
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
class DcloneDemo
{
DcloneDemo()throws CloneNotSuportException
{
Student s1=new Student(“hello”,”200”);
Student s2=(Student)s1.clone();
S2.name=”java”;
System.out.println(s1.name);
Public static void main(String[] arg)
{
new DcloneDemo();
}
}



Iterator,ListIterator,Enumeration

Enumeration:
This is cursor to retrive the objects one by one.
This interface contains the following two methods.
1.boolean hasMoreElements();
2.Object nextElement();
Enumeration Example:
Import java.util.*;
Class EnumDemo
{
public static void main(String arg[])
{
Vector v= new Vector();
For(int i=0;i<=10; i++)
{
v.addElement(new Integer(i);
}
System.out.println(v); // [0,1,2,3…….10]
Enumeration e=v.elements();
While(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
If(i.IntValue() % 2 ==0)
{
System.out.println(i);
}
}
}
Limitations:
1. We can get Enumeration Object only for legacy classes (Vector,Stack,Hashtable,Properties,Dictionary,Enumeration)
2. While iterating the Objects of enumeration we can get only read-access.
i.e while iterating we are not allowed to perform any remove or modify operation.
Iterator:
This can be applied for any collection implemented class (legacy and non-legacy)
While iterating the objects we are allowed to perform remove operation also, in addition to read operation.
This interface contain the following there methods
Boolean hasNext()
Object next();
Void remove()

Iterator Example:
Import java.util.*;
Class IteratorDemo
{
public static void main(String arg[])
{
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++)
{
l.add(new Integer(i);
}
System.out.println(i); // 0,1,2,3,……9
Iterator itr=l.iterator();
While(itr.hasNext())
{
Integer i=(Integer)itr.next();
If(i.intValue() % 2==0)
{
System.out.println(i);
}
else
{
itr.remove();
}
}
System.out.println(l); [0,2,4,6,8]
}
}
}

List Iterator:
List iterator is the child interface of iterator .this can be applicable only for list implemented classes (arraylist,linkedlist,vector and stack).
This is a bidirectional cursor .we can move either to forward or backward direction
While iterating ,we are allowed to replace existing element with the new element ,we are allowed to add new elements and still we can perform remove operation also.
ListIterator defines the following methods.
1.boolean hasNext();
2.boolean hasPrevious();
3.Object next();
4.Object previous();
5.int nextIndex();
if there is no next element it just simply return the size of the list.
6.int previousIndex()
Return -1 if there is no previous index.
7.void remove()
8.void set()
9.void add()

ListIterator Example:
Import java.util.*;
Class ListIterDemo
{
public static void main(String arg[])
{
LikedList l=new LinkedList();
L.add(“laxman”);
l.add(“chandu”);
l.add(“ravi”);
l.add(“raju”);
System.out.println(l);
ListIterator lt=l.listIterator();
While(lt.hasNext())
{
String s=(String)lt.next();
If(s.equals(“laxman”))
{
lt.remove(); or lt.set(“scjp”);
}
}
System.out.println(l);
}
}

Friday, February 6, 2009

java Collection frame work

examples Collections