top of page

1.Collections

 

An array is an indexed collection of fixed number of homogenous data elements.

Limitations of Objective type arrays

  • Arrays are fixed in size. i.e.  Once we created an array there is no chance of increasing or decreasing the size based on our requirement. Hence to use arrays concept compulsory we should know the size in advance which may be not possible always.

  • Arrays can hold only homogeneous data type elements.

Eg. Student [] s = new Student[10];

S[0] = new Student();

S[1]= new “durga”;CE : Incompatible types found : java.lang. String, required: student

We can overcome this limitation by using object type Arrays

Object[] a = new Object[10];

a[0] = new Student();

a[1]=new customer();

a[2]=new “durga”;

  • Arrays concept is not implemented based on some data structure hence readymade method support is not available for arrays for every requirement programmer is responsible to write the code.

To overcome the above limitations we should go for collections

  • Collections are growable in nature i.e. based on our requirement we can increase or decrease the size.

  • Collections can hold both homogenous and heterogeneous elements.

  • For every collection underlying datastructure is available hence readymade method support is available for every requirement.

2.Difference between Arrays and collections.

Arrays

  • Arrays are fixed in size

  • Arrays can hold only homogenous data elements.

  • W. r. t to memory arrays concept is not recommended to use

  • W.r.t to performance arrays are recommended to use.

  • Arrays concept is not implemented based on some data structure hence readymade method support is not available.

  • Arrays can hold both primitives and object types.

 

  • Collections are growable in nature.

  • Collections can hold both homogeneous and heterogeneous elements.

  • W.r.t memory collections are recommended to use.

  • W.r.t performance collections are not recommended to use.

  • Every collection class is implemented based on some data structure hence for every requirement there are readymade methods support is available.

  • Collections can hold only object types but not primitives.

Collection

If we want to represent a group of objects as a single entity then we should go for collection

Collection framework

It defines several classes and interfaces which can be used to represent a group of objects as single entity.

Java – collection,  collection framework

C++ - container, STL (Strndard template library)

9 key interfaces of collection frame work

  • Collection

  • List

  • Set

  • Sortedset

  • Navigableset

  • Queue

  • Map

  • Sortedmap

  • Navigablemap

 

  • Collection (I)

If we want to represent a group of individual objects has a single entity then we should go for collection Interface.

There is no concrete class which implements collection interface directly.

Collection v collections

collection is an interface which can be represented as a group of individual objects as a single entity.

Where as collections is utility class to define several utility methods for collections objects.

  • List (I)

Its child interface of collection

If we want to represent a group of individual objects as a single entity where insertion order is preserved an duplicate objects are allow then we should go for List.

Collection (I) 1.2

List (I) 1.2

ArrayList (C)1.2         LinkedList(C)1.2        Vector(C) 1.0

                                                                        Stack(C) 1.0        legacy classes

In 1.2 version vector & stack classes are reengineered to implement list interface.

  • Set(I)

It’s the child interface of collection

If we want to represent a group of individual object as a single entity where insertion order is not preserved and duplicates are not allowed then we should go for set.

Collection(I) 1.2

Set (I) 1.2

Hashset (C) 1.2

LinkedHashset(C) 1.4

  • Sortedset (I)

It’s the child interface of set

If we want to represent a group of individual objects according to sorting order without duplicates then we should go for sorted set.

  • Navigableset(I)

It’s the child interface of sortedset

It defines several methods which can we used for navigational purpose.

 

Collection(I) 1.2

 

Set(I) 1.2

 

Sortedset(I) 1.2

 

Navigableset(I) 1.6

 

Treeset (C) 1.2

 

  • Queue(I)

It’s the child interface of collection

If we want to represent a group of individual objects prior to processing then we should go for queue.

 

Collecton (I) 1.2

 

Queue (I) 1.5

 

  •  

Note : all the above interfaces (Collection, list, set, sortedset, navigablest queue) meant for representing for individual objects. If we want to represent a group of objects as a key-value pair then we should go for map.

  • Map

It’s the child interface of collection

If we want to represent a group of objects as a key value pairs where duplicates keys are not allowed but values are allowed.

 

Map (I) 1.2

Dictionary (AC)

Hashmap 1.2identityhashmap 1.2weakhashmap 1.2hashtable

 

Linkedhashmap 1.4properties 1.0

 

  • sortedMap

it’s the child interface of map

if we want to represent a group of elements into key value pairs where keys are into some sorting order, then we should go for sortedmap.

  • Navigablemap (I)

It’s the child interface of sortedmap

Its defines several methods for navigation purposes

Map (I) 1.2

 

Sortedmap(I) 1.2

 

Navigablemap (I) 1.6

 

treeMap (c) 1.2

 

note : In collection framework the following are legacy characters

  • Enumeration (I)

  • Vector (C)

  • Property (c)

  • Dictionary (AC)

  • Stack (c)

  • Hashtable (c)

 

  • Collection Interface

if we want to represent a group of individual elements in to a single entity then we should use collection interface.

Its defines most common general methods which are applicable for any collection object.

Collection interface defines the following methods.

 

  • boolean add(object o)

  • boolean addAll(collection c)

  • Boolean remove(object o)

  • Boolean removeall(collection c)

  • Boolean retainall (collection c)  To remove all objects except those present in c

  • Void clear ()

  • Boolean contains(object o)

  • Boolean containsAll((collection c)

  • Boolean isEmpty ()

  • Int size();

  • Object[] toArray();

  • Iterator iterator()

    List interface

it’s the child interface of collection interface

 

if we want to represent a group of individual object where insertion order is preserved and duplicates are allowed then we should go for List.

 

We can differentiate duplicate objects and we can maintain insertion order by using index hence index plays very important role in List.

 

List interface defines the following specific methods.

  • Boolean add(int index, object o)

  • Boolean addAll(int index, collection c)

  • object get(int index)

  • object remove(int index)

  • object  set(int index, object new) to replace the element present at specified index with provided object and return old object

  • int indexOf(object o) returns index of first occurrence of ‘o’

  • int lastIndexOf(object o)

  • ListIterator listIterator();

    ArrayList ( c )

  • the underlying data structure is resizable array or growable array

  • insertion order is preserved

  • duplicate objects are allowed

  • heterogeneous objects are allowed (except Treeset, treemap heterogeneous object allowed)

  • null insertion is possible

constructors

  • ArrayList l = new ArrayList ();

Creates an empty ArrayList object with default initial capacity 10, once ArrayList reaches its max capacity a new ArrayList object will be created with

 

New capacity = ( CurrentCapacity * 3/ 2) + 1

  • ArrayList l = new ArrayList(int initial capacity);

Creates an empty ArrayList object with the specified initial capacity

  • ArrayList l = new ArrayList(Collection c)

Creates an equivalent ArrayList object for the given collection object.

This constructor meant for interconversion between collection object.

 

Eg. Import java.util.*;

Class ArrayListDemo {

P. s. v. main(String args[]){

ArrayList l = new ArrayList ();

  •  

  •  

  •  

  •  

s.o.p (l);[a, 10, a, null]

  •  

s.o.p (l);[a, 10,null]

l.add(2, “m”);

  •  

  •  

  •  

  •  

 

Usually we can use collections to hold and transfer data to support this requirement every collection class implements serializable and cloneable interface

ArrayList and Vector class implements interace so that we can access any random elements with the same speed.

 

Eg. ArrayList l1 = new ArrayList ();

LinkedList l2 = new LinkedList();

s.o.p (l1 instanceOf serializable);//true

s.o.p (l2 instanceOf cloneable) //true

s.o.p (l1 instance of RandomAccess) // true

s.o.p(l2 instance of RandomAccess) //false

 

  • difference between ArrayList and Vector.

  • No method present in A.L is synchronized

  • Multiple threads can operate simultaneously on the ArrayList hence ArrayList object is not Thread safe.

  • Relatively performance is high

  • Introduced in 1.2 version and its non legacy

Vector

  • Every method present in vector is synchronized.

  • At a time only one thread is allowed to operate on the vector object and hence vector is thread safe.

  • Relatively performance is low

  • Introduced in 1.0 and its legacy

How to get synchronized version of ArrayList ?

Collections class contain the following method to get the synchronized version of arraylist

Pulic static List synchronizedList (List l)

Eg.

ArrayList l = new ArrayList ();

List   l1 = collections.synchronized ( l )

Similarly we can get synchronized version of set and map objects by using the following methods.

Public static set synchronizedSet (Set s)

Public static Map synchronizedMap (Map m)

  • ArrayList is best choice if our frequent operation is retrieval operation

  • ArrayLIst is   worst choice if the insertion and deletion operation in middle because it requires several shift operation.

    LinkedList

  • The underlying data structure is double linkedlist

  • Insertion order is preserved.

  • Duplicate objects are allowed.

  • Heterogeneous objects are allowed

  • Null insertion is possible

  • Implements serializable and clonable but not RandomAccess interface.

  • LinkedList is the best choice if our operation is insertion / deletion in the middle.

  • LinkedList is the wrost choice if our operation is retrieval operation.

  • Usually we use LinkedList  to implement stack and queue to provide support for this requirement, LinkedList class defines the following six specific methods.

Void addFirst(object o)

Void addLast(Object o)

Object getFirst()

Object getLast()

Object removeFirst()

Object removeLast()

  • Constructors

  • linkedList l = new LinkedList(); created an empty LinkedList object

  • LinkedList l = new LinkedList(Collection c);

Eg.

Class LinkedListDemo {

p.s.v.main(String args[]){

LinkedList l = new LinkedList();

l.add(“durga”);

l.add(30);

l.add(null);

l.add(“durga”);

l.add(0, “software”);

l.add(0. “venky”);

l.removeLast();

l.addFirst(“ccc”);

s,.o.p(l);  [ccc, venky, software, durga, 30, null]

}

}

  • Vector

  • the underlying data structure is resizeable array and growable array.

  • Insertion order is preserved

  • Duplicate objects are allowed

  • Null insertion is possible

  • Implements serializable, clonable and RandomAccess interfaces.

  • Every object present in the vector is synchronized and hence vector object is ThreadSafe

  • Best suitable if our frequent operation is retrival

  • Worst choice if our frequent operation is insertion of deletion in the middle

Vector specific methods.

To add objects

add(object c) – c

add( int index, object o) – L

addElement( object o) – V

To remove ements

remove(object o) – C

removeElement(object o) – V

remove (int index)  - L

removeElementAt (int index) -  V

clear() – C

removeAllElements () –V

To retrieve elements

Object get(int index) – L

Object elementAt(int index) – V

Object firstElement() – V

Object lastElement() – V

Other elements

int size()

int capacity ()

Enumeration elements()

Constructors

  • Vector v = new Vector () Creates an empty vector object with default initial capacity 10. Once vector reaches its max capacity a new vector object will be created with double capacity i.e

 

New capacity = 2 * current capacity

  • Vector v = new Vector (int initial capacity)

  • Vector v = new Vector (int initialcapacity, int incrementalcapacity);

  • Vector v  = new Vector(Collection c)

Eg. Class VectorDemo {

p.s.v.main(String args[]){

Vector v = new Vector();

s.o.p (v.capacity());

for(int i=0; i<=10; i ++){

 

  • Stack

  • It’s the child interface of vector

  • If we want to represent objects according to last-in-first out order than we should go for stack (LIFO order applicable only for removable)

It contains only one contructor

Stack s = new Stack();

Methods

  • Object push(Object o) to insert an object into the stack

  • Object pop() to remove and return top of the stack

  • Object peek() to return top of the stack without removal

  • Boolean empty() returns true if stack is empty

  • Int search(Object o) returns offset if the element is available otherwise return -1

Eg:

Class stackDemo {

p.s.v.main(String args[]){

Stack s = new Stack();

s.push(“A”);

s.push(“B”);

s.push(“C”);

s.o.p(s);

s.o.p(s.search(“a”));

s.o.p(s.search(“z”));

}

o/p [a,b.c]

3

-1

The 3 cursors of java

  • if we want to retrieve objects one by one from the collection then we should go for cursor.

  • There are 3 cursors are available in ajva

  • Enumeration

  • Iterator

  • Listiterator

  • Enumeration

we can use enumeration object to get objects one by one from legacy collection object

  • We can create enumeration object by using elements() method

Enumeration e = v.elements()

 

  • Enumeration object defines two methods.

Public Boolean hasMoreElements()

Public object nextElement()

Eg.

Class EnumerationDemo{

p.s.v.main(String args[]){

Vector v = new Vector();

For(int i=0; i<=10;i++){

v.addElement(i);

}

 s.o.p(v); [0,1,………10]

enumeration e = v.elements();

while(e.hasMoreElements()){

Integer i= (Integer)e.nextElement();

If(I % 2 == 0){

s.o.p(i);

}

S.o.p(v);

}

}

}

Limitations of enumeration

  • Enumeration concept is applicable only for legacy classes and it is not a universal cursor.

  • By using enumeration we can get only read capability and we can’t perform remove operation.

  • To overcome the limitation we should go for Iterator

  • Iterator

 We can use iterator for any collection object to get objects one by one from the collection. It’s a universal cursor.

While using iterator we can perform remove operation in addition to the read operation

We can get iterator object by using iterator() method of collection Interface.

Public Iterator iterator()

Iterator itr = c.iterator();     where c is any collection object

Iterator interface defines the following 3 methods.

  • Public Boolean hasNext()

  • Public Object next()

  • Public void remove()

Eg.

Class IteratorDemo {

p. s. v. main(String args[]){

ArrayList ls = new ArrayList();

For(int i=0; i<=10; i++){

Ls.add(i);

}

s.o.p(ls);

Iterator itr = ls.iterator();

While (itr.hasNext()){

Integer i = (Integer)Itr.next();

If(i%2==0){

s.op(i);

}else{

Itr.remove();

}

s.o.p(ls)

}

}

}

Limitation

By using Enumeration and Iterator we can move only forward directions and we cannot move back ward direction and it is unidirectional.

By using Iterator we can perform read and remove operation but there is no method available for replace and add new operations to the collection.

  • ListIterator

By using ListIterator we can move either forward or backward directions. It’s a bidirectional cursor.

While iterating objects from ListIterator we can perform read and remove operations, in addition we can add new objects and replace exiting objects.

We can create ListIterator using ListIterator() method from List interface.

Publc ListIterator l.ListIterator();

ListIterator defines following methods.

Public Boolean hasNext();

Public object next();

Public int nextIndex();

Public Boolean hasPrevious();

Public Object previous();

Public int previousIndex();

Public void remove();

Public void set(Object new);

Public void add(Object new);

Class ListIterator {

Public static void main(String args[]){

LinkedList l = new LinkedList();

l.add(“bala”);

l.add(“chiru”);

l.add(“nag”);

s.o.p(l);

ListIterator l = l.listIterator();

While(l.hasNext()){

String str= (String)l.next();

Str.equals(“venki”){

l.remove();

}

If(str.equals(“chiru”)){

l.set(“charan”);

}

If(str.equals(“nag”))

{

l.add(“chaitu”);

}

}

}

}

The most powerful cursor among three is ListIterator but it is applicable only for List object.

 

 

Property

enumeration

Iterator

listIterator

Its legacy

Yes

No

no

Applicable for

Only legacy

Any collection object

Any list object

Movement

Single (forward)

Single (forward)

bidirectional

Hot to get

Elements()

Iterator()

listIterator()

Accessibility

read

Read, remove

Read, remove, add, replace

Methods

2 methods, hasMoreElement(), nextElement()

3 methods

hasNext(), next(), remove()

9 mehods

hasNext(), next(), nextIndex(), hasPrevious(), previous(), previousIndex(),set(),remove(),add()

 

  • Set Interface

It’s the child interface of collection

If we want to represent a group of elements individual elements into single entity where insertion order is not preserved and duplicates are not allowed.

Collection (I)

Set (I)

HashSet                       SortedSet(I)

LinkedHashSet                       NavigableSet(I)

                                    TreeSet

  • Set interface doesn’t contain new methods, it should use collection interface methods

    HashSet

  • The underlying data structure is hashtable.

  • Insertion order is not preserved and duplicate object are not allowed

  • Duplicate objects are not allowed, if we try to insert duplicate objects we won’t get any C.E & R.E errors simply add method returns false.

  • Heterogeneous objects are allowed.

  • Null insertion is possible

  • HashSet implements serializable and clonable interface

  • If our frequent operation is search this is the best option.

Constructors

  • HashSet h = new HashSet()

Creates an empty HashSet object with default initial capacity 16 and default fill ratio (load factor) 0.75

  • HashSet h = new HashSet(int initialcapatity);

Creates an empty hashset object with specified initial capacity and default fill ratio 0.75

  • HashSet h = new HashSet(int initialcapatity, int floatratio)

Eg:

Class Hashsetdemo {

p.s.v. main(String arg[]){

HashSet h = new HashSet();

h.add(“b”);

h.add(“c”);

h.add(“d”);

h.add(“10”);

h.add(“null”);

s.op(h.add(“z”))

}

}

 Op [null, d, b, c, 10, z]

  • LinkedHashSet

It’s the child class of hashset Its exactly same as HashSet including constructors, methods except the following difference

HashSet

LinkedHashSet

The underlying data structure is hashtable

The underlying datastructure is combination of hashtable and linkedlist

Insertion order is not preserved

Insertion order is preserved

Introduced in 1.2 v

Introducted in 1.4 v

In the above program if we replace HashSet with LinkedHashSet the output is [b,c,d,10,null] i.e insertion order is preserved.

Note : usually we can use LinkedHashSet and LinkedHashMap for implementing cache applications where duplicates are not allowed and insertion order must be preserved.

  • SortedSet

  • It is the child interface of the set

  • If we want to represent a group of individual objects according to some sorting order with out duplicates then we should go for sortedset.

  • Sortedset interface defines the following six specific methods.

  • Object first()

Returns first element of the sortedset

  • Object last()

Returns last element of the sortedset

  • SortedSet headset (Object obj)

Retruns sortedset whose elements are less than obj

  • SortedSet tailSet (Object obj)

Returns the sortedset whose elements are >= obj

  • SortedSet subset (object obj1, object obj2)

Returns sortedset whose elements are >=obj1 and < obj2

  • Comparator comparator()

Retruns comparator object i.e which describes underlying sorting techniques

If we are following default sorting order then this method returns null.

Eg :

101

102

104

107

110

116

117

First () – 101

Last () – 117

Headset – 107 – 101, 102,104

Tailset – 107 – 107, 110,116,117

Subset – 104, 117 – 104, 107, 110

Comparator – null

 

  • TreeSet

 

  • Underlying datastructure is balanced tree

  • Duplicate objects are not allowed

  • Insertion order is not preserved and its based on some sorting order.

  • Null insertion is possible only once

  • Heterogeneous objects are not allowed if we are trying to insert heterogeneous object we will get R.E saying classcastException

Contructors

 

  • TreeSet t = new TreeSet()

Creates an empty TreeSet object where all objects will be inserted according to natural sorting order.

  • TreeSet t = new TreeSet(Comparator c)

Creates an empty Treeset object where as objects wil be inserted according to the customized sorting order which is described by comparator object.

  • Treeset t = new TreeSet(Sortedet s)

  • TreeSet t = new TreeSet(Collection c)

Eg:

Class TreeSetDemo {

p.s.vmain(){

TreeSet t = new Treeset();

t.add(“a”);

t.add(“b”);

t.add(“z”);

t.add(“A”);

t.add(“l”);

t.add(new Integer(1)); //CCE

//t.add(null); //Null pointer exception

 

}

}

Null acceptance

  • For the non empty TreeSet if we are trying to insert null we will get NPE

  • For the empty TreeSet as the first element null insertion is possible but after inserting that null if we are trying to inset any other element we will get NPE

Eg:

Class Treesetdemo {

p.s.v.main(){

TreeSet t = new TreeSet();

t.add(new StringBuffer(“A”));

t.add(new StringBuffer(“Z”));

t.add(new StringBuffer(“L”));

t.add(new StringBuffer(“B”));

s.o.p(t);
}

}

R.E – classcastException

- if we are depending on default natural sorting order compulsory the object should be homogenious and comparable otherwise we will get classcastexception.

 

- An object  is said to be comparable if and only if corresponding class implements comparable interface.

- All wrapper classes and string class implements comparable interface but stringbuffer class don’t implement comparable interface. Hence we are getting CCE in above example.

 

  • Comparable interface

  • Comparable interface present in java.lang package.

  • It contains only one method public

int compareTo(Object obj)

obj1.compareTo(Object obj2)

return –ve iff obj1 has to place before obj2

return +ve iff obj1 has to place after obj2

return 0 iff obj1 equals to obj2

eg:

s.o.p (“a”.compareTo(“z”)) // -ve

s.o.p (“z”.compareTo(“k”)) //+ve

s.o.p (“a”.compareTo(“a”)) //0

s.o.p (“a”.compareTo(“null”)) //NPE

 

  • If we are depending on default natural sorting order internally JVM will call compareTo() to place the objects into the Treeset

Eg:

            TreeSet t = new TreeSet();

            t.add(“a”);

            t.add(“z”);   -ve “z”.compareTo(“a”) – [a,z]

            t.add(“k”);  +ve “k”.compareTo(“a”)     -ve “k”compareTo(“z”) – [a,k,z]

            t.add(null); NPE null.compareTo(“a”)

s.o.p(t);

 

Note : if we are not satisfied with default natural sorting order (or) if the default natural sorting order is not applicable then we can define our own customized sorting order by using comparator

 

Comparable meant for default natural sorting order, where as comparator meant for customized sorting order

 

  • Comparator (I)

  • This interface present in java.util package and contains the following two methods.

  • Public int compare (Object obj1, Object obj2)

Returns –ve iff obj1 has to come before obj2

  •  

Returns 0 iff obj1 and obj2 are equal

  • Public Boolean equals(object obj)

  • Whenever we are implementing comparator interface compulsory we should provide implementation for compare() method.

  • Implementing equals method is optional because its already available in every java class from object class through inheritance.

Eg:

   Class TreeSetDemo {

p.s.v.main(){

TreeSet t = new TreeSet(mew MyComparator());   - line 1

t.add(“10”);

t.add(“0”); +ve compare (0,10)

t.add(“15”); -ve compare(15,10)

t.add(“5”);

t.add(“20”);

t.add(“20”);

s.0.p(t);

 

}

}

 

Class Mycomparator implements comparator

{

Public int compare(Object obj1, Object obj2){

Integer i1= (Integer)Obj1;

Integer i2= (Integer)Obj2;

If(i1 > i2){

Return -1;

}

Else If(i1 < i2){

Return +1

}

Else{

Return 0;

}

}

  • At the line 1 if we are not passing comparator object then JVM internally calls compareTo() method which is meant for default natural sorting order (ascending order)in this case the o/p is [0,5,10,15,20]

  • At line 1 if we are passing comparator object as argument then JVM will call compare() method which is meant for customized sorting order in this case the o/p is [20,15,10,5,0]

 

  • Various possible implementations of compare() method

Class mycomparator implements comparator

{

Public int compare(Object obj1, Object 2){

Integer i1 = (Integer)obj1;

Integer i2 = (Integer)obj2;

Return i1.compareTo(i2);   [0,5,10,15,20]

Return –i1.compareTo(i2); [20,15,10,5,0]

Return i2.compareTo(i1);  [20,15,10,5,0]

Return - i2.compareTo(i1); [0,5,10,15,20]

Return -1; [20,20,5,15,0,10] //reverse of insertion order

Return +1; [10,0,15,5,20,20] ////insertion order

Return 0; [10] // only first element will be inserted and all the remaining elements will be treated as duplicates.

}
}

 

Example 2

Write a pgm to insert string objects into the TreeSet where the sorting order is reverse of alphabetical order

Eg.

Class TreeSetDemo2 {

P s v main(String args[]){

TreeSet t = new TreeSet(new MyComparator());

t.add(“Raja”);

t.add(“shobarani”);

t.add(“rajkumar”);

t.add(“gangabhavani”);

t.add(“ramulamma”);

s.o.p(t);

}

}

 

Class Mycomparator implements Comparator

{

Public int compare (object obj1, object ob2){

String s1= (String)Obj1;

String s2= (String)Obj2;

Return – s1.compareTo(s2);

}

}

Write a pgm to insert StringBuffer objects into the TreeSet where the sorting order is alphabetical order.

Eg.

Class TreeSetDemo

{

P s v main(String args[]){

TreeSet t = new TreeSet(new MyComparator());

t.add(new StringBuffer(“A”))

t.add(new StringBuffer(“Z”))

t.add(new StringBuffer(“K”))

t.add(new StringBuffer(“L”))

s.o.p(t);

}

}

 Class MyComparator implements comparator

{

Public int comparator(Object obj1, Object obj2){

String s1= Obj1.toString();

String s2= Obj2.toString();

Return s1.compareTo(s2)

}

}

 

o/p [A, K, L, Z]

 

NOTE:

If we are defining our own customized sorting then we can insert non – comparable objects also into the TreeSet

 

Write a pgm to insert string and stringBuffer objects into the TreeSet where the sorting order is increasing length order. If two objects having the same length then consider their alphabetical order.

 

Eg. Class TreeSetDemo2{

p.s.v main(String args[]){

TreeSet t = new TreeSet(new MyComparator());

t.add(new StringBuffer(“ABC”));

t.add(new StringBuffer(“AA”));

t.add(“XX”);

t.add(“ABC”);

t.add(“A”);

s.op(t);

}

}

 

Class MyComparator implements Comparator

{

Public int comparator(Object obj1, Object obj2){

String s1 =Obj1.toString();

String s2 = Obj2.toString();

Int l1 = S1.length();

Int l2 =S2.length();

If(l1 < l2){

Retrun -1;

}else if(l1 > l2){

Retrun 1;

}else{

Return s1.compareTo(s2);

}

}

}

NOTE: if we are depending on default natural sorting order then the objects should be homogenous and comparable otherwise we will get CCE

If we are defining our own sorting by comparator then the objects need not be comparable and homogenous.

 

  • Comparable vs Comparator

  • For predefined comparable classes like  string default natural sorting order is already available. If we are not satisfied with that natural sorting order we can define our own sorting by comparator object.

  • For predefined non comparable classes like StringBuffer default natural sorting order is not already available, we can define our own sorting by comparator.

  • For our own classes (like Employee) the person who is writing the class he can define default natural sorting order by implementing comparable interface.

 

  • The person who is using our own classes if he is not satisified with default natural sorting order then we can define his own sorting by using comparator object.

 

  • Comparison table for comparable and comparator interface

 

Comparable

  • This is the interface meant for default natural sorting order

  • This interface present in java.lang package

  • It defines only one method compareTo() method

  • String class, all wrapper classes implements comparable interface

Comparator

  • This interface meant for customized sorting order

  • This interface present in java.util package

  • It defines two methods compare(object obj, object obj2) and equals() methods.

  • The only implemented classes of comparator is collator and RuleBased collator

 

Eg.

 

Class Employee implements Comparator

{

String name;

Int eid;

Employee(String name, int eid){

This.name = name;

This.eid = eid;

}

Public String toString(){

Retrun name +”---”+eid;

}

Public int comparTo(Object obj1){

Int eid1 = this.eid;

Employee e = (Employee)Obj1;

Int eid2 = e.eid();

If(eid1 < eid2 ){

Retrun -1;

} Else if (eid1 > eid2){

Retrun 1;

}else{
return 0;

}

 

Class CompComp {

p.s.v. main(String args[]){

Employee e1 = new Employee(“nag”100,);

Employee e2 = new Employee(“baliab”200,);

Employee e3 = new Employee(“chiru”,50);

Employee e4 = new Employee(“venki”,150);

Employee e5 = new Employee(“nag”,100);

TreeSet t = new TreeSet();

t.add(e1);

t.add(e2);

t.add(e3);

t.add(e4);

t.add(e5);

s.o.p(t);

TreeSet t1 = new TreeSet(new Comparator()){

T1.add(e1);

T1.add(e2);

T1.add(e3);

T1.add(e4);

T1.add(e5);

s.o.p(t1);

}

}

 

Class Mycomparator implements Comparator

{

Public int compare(Object obj1, Object obj2){

Employee e1 = (Employee)obj1;

Employee e2 = (Employee)obj2;

String s1 = e1.nname;

String s2 = e2.name;

Return s1.compareTo(s1);

}

}

  • Comparison table for Set implemented class

 

Property

HashSet

LinkedHashSet

TreeSet

Under lying data structure

Hashtable

Hashtable + linked list

Balanced tree

Insertion order

Not preserved

Preserved

Not preserved

Sorting order

N.A

N.A

Preserved

Heterogeneous object

Allowed

Allowed

Not allowed

Duplicate objects

Not allowed

Not allowed

Not allowed

Null acceptance

Allowed(1)

Allowed(1)

For the empty TreeSet add the first element null insertion is possible in all other cases we will get NPE

 

  • Map (I)

 

  • if we want to represent a group of objects as key – value pairs then we should go for Map both key & value are objects.

  • Duplicate keys are not allowed but values can be duplicated.

  • Each key – value pair is called entry

 

  • There is no relationship between collection and Map.

  • Map is not child interface of collection.

Directory (A.C)

HashMap (C)IdentityHashMap1.4WeakHashMap1.2SortedMap(I)1.2HashTable (c)

 

LinkedHashMap (C )NavigableSortedMap(I)1.6Properties (c )

 

            TreeMap (C )

  • Methods of Map interface

 

  • Object put(Object key, Object value)

  • To add key – value pair to the Map

  • If the specified key is already available then old value will be replaced with new value and old value will be returned.

  •  Void putAll(Map m)

-  To add a group of key – value pair.

  • Object get(Object key)

  • Returns the value associated with specified key

  • If the key is not available then we will get Null.

  • Object remove(Object key)

  • boolean containsKey(Object key)

  • boolean containsValue(Object key)

  • int size()

  • Boolean isEmpty()

  • Void clear()

  • Set KeySet()

  • Collection values()

  • Set entrySet()

 

  • Entry (Interface)

  • Each key – value pair is called Entry

  • Without existing Map Object there is no chance of Entry Object, Hence Interface Entry is defined inside Map interface.

 

Code :

 

Interface Map {

Interface Entry {

Object getKey()

Object getValue()

Object setKey()

Object setValue()

           

bottom of page