Collection Frame Work
--> Anarray isan indexedcollectionof fixednumber,of homogeneousdataelements.
Limitations of Object Array:
decreasing
size basedonour requirement.
always.
Student[]s=newstudent[10];
S[0]=newStudent();
S[1]=newStudent();
S[2]=newCustomer(); //C.Eincompatible type
available .foreveryrequirementcompulsoryprogrammerisresponsibletowrite the logic.Tosolve
above problemsunpeople introducedcollectionconcept.
Advs of collection over arrays
the size.
rycollectionclassisimplementedbasedonsome datastructure hence readymade methods
supportisavailable forrequirement.
Dis adv of collections
Collection:-
 A groupof individual objectsasa single entryiscalledcollection.
 If definesseveral classes&interfaceswhichcanbe usedto representagroupof objectsas a
single entity.
 9-keyinterfacesof collectionsframe work
1) Collection(interface)
It isthe rootinterface of the collectionframe work
It definescommanmethodswhichcanbe applicable foranycollectionobject.
2) List(interface):
 It isthe childinterface of collection.
 If we wantto representagroupof individualobjectswhere insertionorderispreserved and
duplicatedvaluesare allowed thenwe shouldgofor List.
3) Set(interface)
 It isthe childinterface of Collection.
 If we wantto representa group of individual objectswhere duplicatesare not allowed and
insertionorder isnot preservedthenwe shouldgo for “Set”.
4) SortedSet(interface)
we shouldgofor SortedSet
5) NavigableSet(interface)
several methodsfornavigationperposes
6) Queue(interface)
go for queue
7) Map(interface)
o representagroup of objectsas key-value pairsthenwe shouldgofor Map.
Note Map isnot childinterface of Collection.
8) SortedMap(interface)
to representagroup of objectsas key-valuepairsaccordingtosome sorting
order.Thenwe shouldgo forSortedMap.
9 ) NavigableMap(interface):
igationpurposes.
Collectionmethods:
1) booleanadd(Objecto)
2) booleanaddAll(Collectionc)
3) booleanremove(Objecto)
4) booleanremoveAll(Collectionc)
5) booleanretainAll(Collectionc)
6)voidclear()
7)boolean isEmpty()
8)intsize()
9)booleancontains(Objecto)
10)booleancontainsAll(Collectionc)
11)Object[] toArray()
12)Iteratoriterator().
List:-
--> lististhe childinterface of collection
-->if we wantto representagroupmof individual objects where duplicate objectsare allowedand
insertationorder is preservedthenwe should go for List.
-->insertionorderwill be preservedbymeans of index.
-->we can differenciateduplicate objectsbyusingindex.Hence index place isveryimportantrole in
List.
-->Listinterface definesthe followingmethods
1)booleanadd(intindex,ObjectO)
2)booleanaddAll(intindex,Collectionc)
3)Objectremove(intindex)
4)Objectget(intindex)
5)objectset(intindex,Objectnew)
6)intindexOf(objecto)
7)intlastIndexOf(Object o)
8)ListIteratorlistIterator()
subclasse of List:
1)ArrayList(ccver1.2)
2)LinkedList(ccver1.2)
3)Vector(cc,ver1.0)
4)Stack(cc ,ver1.0)
ArrayList(cc):-
-->the underlyingdatastructure forArrayListisResizable ArrayorGrowable Array
-->insertion orderispreserved
-->duplicate objectsare allowed
-->heterogeneousobjectsare allowed
-->null insertionispossible
Constructor:
(1) ArraylistAL= NewArraylist( );
--> CreatesanemptyArray listobject,withdefaultinitialcapacity'10'.
-->Once AL reachesit'smax.capacitythenanew AL objectwill be createdwith
newcapacity = current capacity* 3/2+1
(2)ArrayListL=newArrayList(int initial capacity);
-->Createsanemptyarray listobjectwiththe specifiedinitial capacity.
(3) ArrayListL = newArrayList(Collectionc);
-->CreatesanequivalentArraylistobjectforthe givencollectionobjectsI.e;
thisconstructoris for dancingb/wcollectionobjects.
EX: Importjava.util.*;
classArrayListDemo
{
p.s.v.m(string[] args)
{
ArrayLista= newArrayList( );
a.add (“A”);
a.add (“10”);
a.add(“A”);
a.add(“null”);
s.o.pln(a); [A,10,A,Null]
a.remove(2);
a.add(2,”M”) ; [A,10,M,Null]
a.add(“N”) [A,10,M,null,N]
S.o.pln(a); [A,10,M,null,N]
}
}
}
S.o.pln(a.size( ));//5
a.clear( ) ; //[ ]
a.addAll (a);//[A,10,M,null,N,A,10,M,null,N]
NOTE:
-->IneverycollectionclasstoString( ) isoverriddentoreturn
itscontentdirectlyinthe followingformatt.
[obj1,obj2,obj3------]
-->Usuallywe canuse collectiontostore & transferobjectstoprovide
supportfor thisrequirement everycollectionclassimplementsserializable&clonable interfaces.
-->ArrayListandvectorclassesimplementsRandomAccessinterfacesothatany randomelementwe
can access withsame speed.Hence if ourfrequentoperationisretrival opretaitonthenbestsutable
datastructure isArrayList(advantage)
-->if ourfrequentopreationisinsertionordeletioninthe middle thenArrayLististhe worestchoice
,because itrequiredseveral shiftoperations.(disadv)
-->All Vectormethodsare synchronized.
-->All Arraylistmethodsare notsynchronized
Note:
-->if ourfrequentopreationisinsertionordeletaioninthe middle thenAryayListisnot
recommended.Tohandle thisrequirementwe shouldgoforLinkedList.
LinkedList:
→ the underlyingdatastructure is double LinkedList
→ insertionorderispreserved
→ Heterogeneousobjectsare allowed
→ null insertionispossible
→ implementsSerializable andClonable interfacesbutnotRandomAccess interface.
→ bestsutable if ourfrequentopreationinsertionordeletioninthe middle
→ worrestchoice if outfrequentoperationisretrival.
Constructor:
1) LinkedListl=newLinkedList();
create an emptylinkedlistobject
2) LinkedListl=newLinkedList(Collectionc)
create LinkedListobjectwithexistingcollectionobjects
LinkedListspecificmethods:
usuallywe canuse LisnkedListtoimplementsStacksandQueuestosupportthisrequirements
.LinkedListclassdefine the followingsix specificmethods
1)voidaddFirst(ObjectO)
2)voidaddLast(ObjectO)
3)ObjectremoveFirst()
4)ObjectremoveLast()
5)ObjectgetFirst()
6)ObjectgetLast()
ex:
importjava.util.*
classLinkedListDemo
{
p s v main(String[]args)
{
LinkedListl=newLinkedList()
l.add(“satya”);
l.add(30);
l.add(null);
l.add(“satya”);
l.set(0,”mat”)
l.set(0,”pavan”);
l.removeLast();
l.addFirst(“hello”);
S.O.P(l);
}
}
o/p[hello,pavan,mat,30,null,satya]
cursors:
types of Cursors:
→if we want to get objects one by one form the collection we sholud go for cursor
→ there are three types of cursors available in java.
I) Enumetration(1.0v)
II) Iterator(1.2v)
III) ListIterator(1.2v)
1) Enumeration:
→ it is cursor to retrive objects one by one form the collection
→ it is applicable for legacy classes
→ we can create Enumeration object by using elements()
public Enumeration elements()
eg:
Enumration e=v.elements();
here v is Vector object
→ Enumeration define following methods
1) public boolean hasMoreElements()
2) public Object nextElement();
Ex:-
import java.util.*;
class Enumeration
{
p s v m(String [] args)
{
Vector v=new Vector()
for(int i=0;i<=10;i++)
{
v.addElement(i);
}
S.O.P(v); o/p[0,1,2,........10]
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer I=new (Integer)e.nextElements();
if(I%2==0)
S.O.P(I); o/p[0,2,4,6........10]
}
S.O.P(v); o/p[0,1,2,........10]
}
}
Limitations of Enumeration:-
--> Enumeration concept is applicable only for legacy classes and hence it is not a universal
cursor
--> by using enumeration we can get only ReadAccess and we can't perform any remove
operations
--> to over come these limitaions Sun people intruoduced Itreator in 1.2 ver
Iterator:-
--> we can apply Itreator concept for any Collection object. It is a universal cursor.
--> while itreator we can perform remove opreation also ,inaddition to read operation.
-->we can get Iterator object by iterator() of collection interface.
Iterator itr=c.iterator();
--> Itreator interface defines the following 3 methods.
1)public boolean hasNext();
2)public Obect next()
3)public void remove();
import java.util.*;
class IteratorDemo
{
public static void main(String[]args)
{
ArrayList l=new ArrayList();
for(int i=0;i<=10;i++)
{
l.add(i);
}
S.O.P(l); o/p[0,1,2,3........10]
Iterator itr=l.iterator();
while(itr.hasNext())
{
Integer I= (Integer)itr.next();
If(I%2==0)
{
S.O.P(I);
}
else
{
Itr.remove();
}
}
S.O.P(l); o/p[0,2,4,6,8]
}
Limitations of Iterator:
In the case of iterator and enumeration we can always move towards the forwards direction
we can’t move backward direction i.e these cursors are single direction cursors but not
bidirectional.we can’t perform replacement and edition of new objects. To solve this
problem SUN people introduced ListIterator in 1.2 version.
ListIterator:-
Iterator we can move either to forward or to the backword
direction . i,e ListIterator is Bidirectional cursor.
in addition to read remove operations.
ator ListIterator object by using ListIterator of List interface
Methods:
1)public boolean hasNext()
2)public Object next()
3)public int nextIndex()
4)public boolean hasPrevious()
5)public Object previous()
6)public int previousIndex()
7)public void remove()
8)public void set(Object new)
9)public void add(Object new)
import java.util.*;
class ListIteratorDemo
{
Public static void main(String []args)
{
LinkedList l=new LinkedList();
l.add(“pavan”);
l.add(“chiru”);
l.add(“venky”);
l.add(“arjune”);
l.add(“nag”);
S.O.P(l);
ListIterator ltr=l.listIterator();
while(ltr.hasNext())
{
String s=(String)ltr.next();
If(s.equals(“venky”))
Ltr.remove();
If(s.equals(“chiru”))
Ltr.set(“charan”);
If(s.equals(“nag”))
Ltr.add(“chaitanya”);
}
S.O.P(l);
}
}
Set(CC)
 Setis childinterface of Collection.
 If we wantto representagroupof objectswhere duplicatesare notallowedandinsertion
orderis notpreservedthenwe shouldgoforSet.
 HashSet(CC):-
 The underlyingdatastructure isHashtable
 Duplicate objectsare not allowed.
 If we are tryingto add duplicate objectswe won’tgetanyerroradd() simplyreturnsfalse
 Heterogeneousobjectsare allowed
 Null insertionispossible (onlyonce) becauseduplicatesare notallowed
 HashsetimplementsSerializable andClonable interfaces
Constructor
 HashSeth=newHashSet();
 Createsan emptyHashSetobectswithdefaultintial capacity16 anddefaultfillratio
0.75(75%)
 HashSeth=newHashSet(intinitcapacity);
 Createsan emptyHashSetobectswiththe specified intialcapacityand defaultfillratio
0.75(75%)
 HashSeth=newHashSet(intinitcapacity,floatfillratio)
 HashSeth=newHashSet(Collectionc)
import java.util.*;
class HashSetDemo
{
HashSet h=new HashSet();
h.add(“B”);
h.add(“C”);
h.add(“D”);
h.add(“Z”);
h.add(“null”);
h.add(10);
S.O.P(h.add(“Z”)); o/p false
S.O.P(b); o/p[null ,D,B,C,10,Z]
}
}
note : insertion order is not preserved
SortedSet(I):
we
shouldgofor SortedSet.
1)Objectfirst()
Returnsthe firstelementof SortedSet.
2)Objectlast()
Returnsthe firstelementof SortedSet.
3)SortedSetheadSet(Objectobj)
Returnsthe SoredSetwhose elementsare lessthanobj
4)SortedSettailSet(Objectobj)
Returnsthe SoredSetwhose elementsare graterthanare equal toobj
5)SortedSetsubSet(Objectobj1,Objectobj2)
Returnsthe SoredSetwhose elementsare >= to obj1 and<obj2
6)Comparatorcomparator()
 If we use defaultnatural sortingorderthenwe will getnull
 Eg: [100,101,103,104,107,109]
first() returns100
last() returns109
headset(104) returns[100,101,103]
tailSet(104) returns[104,107,109]
subset(101,107) returns[101,103,104]
Comparator() returnsnull
Note:
TreeSet(c)
Exceptionandnull insertion
isnot possible
Constructors:
TreeSett=newTreeSet();
TreeSett=newTreeSet(Comparatorc)
createsan emptyTreeSetobjectwhere sortingorderis cunstomizedsortingorderspecifiedby
Comparatorobject.
TreeSett=newTreeSet(Collectionc)
TreeSett=newTreeSet(SortedSetc)
importjava.util.*;
classTreeSetDemo
{
P S V main(String[]args)
{
TreeSett=newTreeSet();
t.add(“A”);
t.add(“a”);
t.add(“B”);
t.add(“Z”);
t.add(“L”);
//t.add(new Integer(10));//CCEClassCastException
S.O.P(t);[A,B,L,Z,a]
}
}
null acceptance:-
-emptyTreeSetif we are tryingto insertnull we will getNullPointerException
TreeSetaddthe firstelementnullinsertionisalwayspossible.
Importjava.util.*;
ClassTreeSetDemo
{
Publicstaticvoidmain(String[]args)
{
TreeSett=newTreeSet();
t.add(newStringBuffer(“A”));
t.add(newStringBuffer(“Z”));
t.add(newStringBuffer(“L”));
t.add(newStringBuffer(“B”));
}
}
o/pCCE
comparable otherwisewe willget ClassCastException.
interface.
implementscomparableinterface .henceinthe above example we gotCCE.
Comparable Interface:-
PublicintcompareTo(Objectobj)
Obj1.comapreTo(obj2)
–ve if obj1 has to come before obj2
returns+ve if obj1 has to come afterobj2
importjava.util.*;
classTest
{
P S V M(String[]args)
{
S.O.P(“A”.compareTo(”Z”));// -ve =>-25
S.O.P(“K”.compareTo(”A”));//+ve =>15
S.O.P(“A”.compareTo(”A”));//0
}
}
whenwe are dependingondefaultnatural sortingorderinternallyJVMcallscomareTo()
–type JVMindetifiesthe locationof the elementinsortingorder
obj1.compareTo(obj2)
ctinTreeSet
–ve if obj1 has to come before obj2
Treesett=newTreeSet();
t.add(“Z”);
-ve
-ve
-->+ve
-ve
//t.add(null);//NPE
}
o/p[D,K,M,Z]
if we are not satisfiedwithdefaultnatural sortingorder(or) if the defaultsortingorderisnot
available thenwe candefine ourowncustomizedsortingbyusingcomparator.
Comparator(I)
s.
1) Publicintcompare(objectobj1,Objectobj2)
–ve if obj1 has to come before obj2
2)publicbooleanequals(Objectobj)
implementationforcompare() ,2nd
methodequals() implementationisoptional because itis
alreadyavailable forourclassformobjectclassthrough interface.
Importjava.util.*;
classTreeSetDemo3
{
P S V M(String[]args)
{
t .ad(20);
t .add(0); -------
t.add(15);------
------- -ve
t.add(5); ----
-ve
t.add(10)----
-ve
S .O.P(t);
}
}
classMyComparator implementsComparator
{
P intcompare(Objectobj1,Objectobj2)
{
IntegerI1=(Interger)obj1;
Integeri2=(Integer)obj2;
If(I1<I2)
return+100;
else if(I1>I2)
return-1000;
else
return0;
}
}
mentfor defaultnatural sortingorder.inthiscase the o/pis[0,5,10,15,20]
ismentfor customizedsortingorder.these case the o/pis [20,15,10,5,0]
Various alternatives of implementing compare():-
ClassMyComparatorimplementsComparator
{
P S V main(String[]args)
{
IntergerI1=(Integer)obj1;
IntergerI2=(Integer)obj2;
//return -
//return -
//return -
}
}
tingorderisreverse of alphabetical
order?
importjava.util.*;
classTreesetDemo2
{
TreeSett=newTreeSet(newMyComparator())
t.add(“A”);
t.add(“Z”);
t.add(“k”);
t.add(“B”);
t.add(“a”);
S.O.P(t);
}
}
ClassMyComparatorimplementsComparator
{
publicintcompare(Objectobj1,Objectobj2)
{
Strings1=(String)obj1;
Strings2=obj2.toString();
returns–s1.compareTo(s2);
}
}
Note:InObjectsand StringBufferthere isnocompareTo() ,sowe have toConvertStringBuffer
intoString.
W A P to insertStringand StringBufferobjectsintothe TreeSetwhere the Sortingorder
increasinglengthorder.If twoobjectshavingthe same lengththenconsidertheiralphabetical
order.
Importjava.util.*;
classTreeSetDemo
{
TreeSett=newTreeSet(newMyComparator());
t.add(“A”);
t.add(newStringBuffer(“ABC”));
t.add(newStringBuffer(“AA”));
t.add(“XX”);
t.add(“ABCD”);
t.add(“A”);
S.O.P(t);o/p[A,AA,XX,ABC,ABCD]
}
}
ClassMyComparatorimplementsComparator
{
Publicintcompare(Objectobj1,Objectobj2)
{
Strings1=obj1.toString();
Strings2=obj2.toString();
intl1=s1.length();
intl2=s2.length();
if(l1<l2)
return-1;
else if(l1>l2)
return1;
else
returns1.compareTo(s2);
}
}
W A P to insertStringBufferobjectsintothe TreeSetwhere the sortingorderlsalphabetical
order?
importjava.util.*;
P S V M(String[]args)
{
TreeSett=newTreeSet(newMyComparator());
t.add(newStringBuffer(“A”);
t.add(newStringBuffer(“Z”);
t.add(newStringBuffer(“K”);
t.add(newStringBuffer(“L”);
S.O.P(t); [A,K,L,Z]
}
}
classMyComparator implementsComparator
{
Strings1=obj1.toString();
Strings2=obj2.toString();
returns1.compareTo(s2);
}
}
Map(I):-
-->if we wantto representagroupof objectsaskey-value pairsthenwe shouldgoforMap.Both
key& valuesare objects.
esare objects
-value pairiscalledEntry.
Rollno name
101 satya
key 102 srinu Entry
103 ravi value
104 krishna
105 gagan
there isnorelationshipb/wCollectionandMap.
-value
pairs.
1) Objectput(Objectkey,Objectvalue)
o addkey-value pairtothe map
value will be returned.
2) VoidputAll(Objectkey)
-value pairs
3) Objectget(Objectkey)
ociatedwithspecifiedkey
4) Objectremove(Objectkey)
5) booleancontainsKey(Objectkey)
6) booleancontainsValue(Objectvalue)
7) intsize()
8) voidclear()
9) booleanisEmpty()
10) SetkeySet()
11) Collectionvalues()
12) SetentrySet()
Entry(I)
-valuepairiscalledone Entry.
Hence ,interface Entryisdefine insideMapInterface.
interface Map
{
Interface Entry
{
ObjectgetKey()
ObjectgetValue()
ObjectsetValue()
}
}
HashMap:-
-->the underlyingdatastructure isHashTable
hCode of keys
Constructor:-
HashMap m=newHashMap()
0.75(75%)
ashMap(intinitialcapacity)
importjava.util.*;
classHashMapDemo
{
HashMap m=newHashMap();
m.put(“chiru”,700);
m.put(“balaiah”,800);
m.put(“venkatesh”,1000);
m.put(“nagarjuna”,500);
S.O.P(m);{venkatesh=1000,balaiah=800,chiru=700,nagajuna=500}
S.O.P(m.put(“chiru”,1000)); o/p700
Sets=m.keySet();
S.O.P(s); [venkatesh,balaiah,chiru,nagarjuna]
Collectionc=m.values();
S.O.P(c);[1000,800,1000,500]
Sets1=m.entrySet();
While(its.hasNext())
{
Map.Entry m1=(Map.Entry)its.next();
S.O.P(m1.getKey()+”.......”+m1.getValues());
If(m1.getKey().equals(“nagarjuna”))
m1.setValue(10000);
}
S.O.P(m);
}
}
}
}
LinkedHashMap:-
same as HashMap exceptthe followingdifferences
HashMap LinkedList
1)the underlyingD.SisHashTable HashTable+LinkedList
2)insertionorderisnotpreserved preserved
3)introducedin1.2 version 1.4 version
e replacingHashMap withLinkedHashMapthe followingisthe
O/P
{chiru=700 ,balaiah=800,venkatesh=1000,nagajuna=500}
Insertionorderispreserved.

Collection frame work

  • 1.
    Collection Frame Work -->Anarray isan indexedcollectionof fixednumber,of homogeneousdataelements. Limitations of Object Array: decreasing size basedonour requirement. always. Student[]s=newstudent[10]; S[0]=newStudent(); S[1]=newStudent(); S[2]=newCustomer(); //C.Eincompatible type available .foreveryrequirementcompulsoryprogrammerisresponsibletowrite the logic.Tosolve above problemsunpeople introducedcollectionconcept. Advs of collection over arrays the size. rycollectionclassisimplementedbasedonsome datastructure hence readymade methods supportisavailable forrequirement. Dis adv of collections Collection:-  A groupof individual objectsasa single entryiscalledcollection.  If definesseveral classes&interfaceswhichcanbe usedto representagroupof objectsas a single entity.  9-keyinterfacesof collectionsframe work 1) Collection(interface)
  • 2.
    It isthe rootinterfaceof the collectionframe work It definescommanmethodswhichcanbe applicable foranycollectionobject. 2) List(interface):  It isthe childinterface of collection.  If we wantto representagroupof individualobjectswhere insertionorderispreserved and duplicatedvaluesare allowed thenwe shouldgofor List. 3) Set(interface)  It isthe childinterface of Collection.  If we wantto representa group of individual objectswhere duplicatesare not allowed and insertionorder isnot preservedthenwe shouldgo for “Set”. 4) SortedSet(interface) we shouldgofor SortedSet 5) NavigableSet(interface) several methodsfornavigationperposes 6) Queue(interface) go for queue 7) Map(interface) o representagroup of objectsas key-value pairsthenwe shouldgofor Map. Note Map isnot childinterface of Collection. 8) SortedMap(interface) to representagroup of objectsas key-valuepairsaccordingtosome sorting order.Thenwe shouldgo forSortedMap.
  • 3.
    9 ) NavigableMap(interface): igationpurposes. Collectionmethods: 1)booleanadd(Objecto) 2) booleanaddAll(Collectionc) 3) booleanremove(Objecto) 4) booleanremoveAll(Collectionc) 5) booleanretainAll(Collectionc) 6)voidclear() 7)boolean isEmpty() 8)intsize() 9)booleancontains(Objecto) 10)booleancontainsAll(Collectionc) 11)Object[] toArray() 12)Iteratoriterator(). List:- --> lististhe childinterface of collection -->if we wantto representagroupmof individual objects where duplicate objectsare allowedand insertationorder is preservedthenwe should go for List. -->insertionorderwill be preservedbymeans of index. -->we can differenciateduplicate objectsbyusingindex.Hence index place isveryimportantrole in List. -->Listinterface definesthe followingmethods 1)booleanadd(intindex,ObjectO)
  • 4.
    2)booleanaddAll(intindex,Collectionc) 3)Objectremove(intindex) 4)Objectget(intindex) 5)objectset(intindex,Objectnew) 6)intindexOf(objecto) 7)intlastIndexOf(Object o) 8)ListIteratorlistIterator() subclasse ofList: 1)ArrayList(ccver1.2) 2)LinkedList(ccver1.2) 3)Vector(cc,ver1.0) 4)Stack(cc ,ver1.0) ArrayList(cc):- -->the underlyingdatastructure forArrayListisResizable ArrayorGrowable Array -->insertion orderispreserved -->duplicate objectsare allowed -->heterogeneousobjectsare allowed -->null insertionispossible Constructor: (1) ArraylistAL= NewArraylist( ); --> CreatesanemptyArray listobject,withdefaultinitialcapacity'10'. -->Once AL reachesit'smax.capacitythenanew AL objectwill be createdwith newcapacity = current capacity* 3/2+1 (2)ArrayListL=newArrayList(int initial capacity);
  • 5.
    -->Createsanemptyarray listobjectwiththe specifiedinitialcapacity. (3) ArrayListL = newArrayList(Collectionc); -->CreatesanequivalentArraylistobjectforthe givencollectionobjectsI.e; thisconstructoris for dancingb/wcollectionobjects. EX: Importjava.util.*; classArrayListDemo { p.s.v.m(string[] args) { ArrayLista= newArrayList( ); a.add (“A”); a.add (“10”); a.add(“A”); a.add(“null”); s.o.pln(a); [A,10,A,Null] a.remove(2); a.add(2,”M”) ; [A,10,M,Null] a.add(“N”) [A,10,M,null,N] S.o.pln(a); [A,10,M,null,N] } } } S.o.pln(a.size( ));//5 a.clear( ) ; //[ ] a.addAll (a);//[A,10,M,null,N,A,10,M,null,N] NOTE:
  • 6.
    -->IneverycollectionclasstoString( ) isoverriddentoreturn itscontentdirectlyinthefollowingformatt. [obj1,obj2,obj3------] -->Usuallywe canuse collectiontostore & transferobjectstoprovide supportfor thisrequirement everycollectionclassimplementsserializable&clonable interfaces. -->ArrayListandvectorclassesimplementsRandomAccessinterfacesothatany randomelementwe can access withsame speed.Hence if ourfrequentoperationisretrival opretaitonthenbestsutable datastructure isArrayList(advantage) -->if ourfrequentopreationisinsertionordeletioninthe middle thenArrayLististhe worestchoice ,because itrequiredseveral shiftoperations.(disadv) -->All Vectormethodsare synchronized. -->All Arraylistmethodsare notsynchronized Note: -->if ourfrequentopreationisinsertionordeletaioninthe middle thenAryayListisnot recommended.Tohandle thisrequirementwe shouldgoforLinkedList. LinkedList: → the underlyingdatastructure is double LinkedList → insertionorderispreserved → Heterogeneousobjectsare allowed → null insertionispossible → implementsSerializable andClonable interfacesbutnotRandomAccess interface. → bestsutable if ourfrequentopreationinsertionordeletioninthe middle → worrestchoice if outfrequentoperationisretrival. Constructor: 1) LinkedListl=newLinkedList(); create an emptylinkedlistobject 2) LinkedListl=newLinkedList(Collectionc) create LinkedListobjectwithexistingcollectionobjects LinkedListspecificmethods:
  • 7.
    usuallywe canuse LisnkedListtoimplementsStacksandQueuestosupportthisrequirements .LinkedListclassdefinethe followingsix specificmethods 1)voidaddFirst(ObjectO) 2)voidaddLast(ObjectO) 3)ObjectremoveFirst() 4)ObjectremoveLast() 5)ObjectgetFirst() 6)ObjectgetLast() ex: importjava.util.* classLinkedListDemo { p s v main(String[]args) { LinkedListl=newLinkedList() l.add(“satya”); l.add(30); l.add(null); l.add(“satya”); l.set(0,”mat”) l.set(0,”pavan”); l.removeLast(); l.addFirst(“hello”); S.O.P(l); } } o/p[hello,pavan,mat,30,null,satya]
  • 8.
    cursors: types of Cursors: →ifwe want to get objects one by one form the collection we sholud go for cursor → there are three types of cursors available in java. I) Enumetration(1.0v) II) Iterator(1.2v) III) ListIterator(1.2v) 1) Enumeration: → it is cursor to retrive objects one by one form the collection → it is applicable for legacy classes → we can create Enumeration object by using elements() public Enumeration elements() eg: Enumration e=v.elements(); here v is Vector object → Enumeration define following methods 1) public boolean hasMoreElements() 2) public Object nextElement();
  • 9.
    Ex:- import java.util.*; class Enumeration { ps v m(String [] args) { Vector v=new Vector() for(int i=0;i<=10;i++) { v.addElement(i); } S.O.P(v); o/p[0,1,2,........10] Enumeration e=v.elements(); while(e.hasMoreElements()) { Integer I=new (Integer)e.nextElements(); if(I%2==0) S.O.P(I); o/p[0,2,4,6........10] } S.O.P(v); o/p[0,1,2,........10] } } Limitations of Enumeration:- --> Enumeration concept is applicable only for legacy classes and hence it is not a universal cursor
  • 10.
    --> by usingenumeration we can get only ReadAccess and we can't perform any remove operations --> to over come these limitaions Sun people intruoduced Itreator in 1.2 ver Iterator:- --> we can apply Itreator concept for any Collection object. It is a universal cursor. --> while itreator we can perform remove opreation also ,inaddition to read operation. -->we can get Iterator object by iterator() of collection interface. Iterator itr=c.iterator(); --> Itreator interface defines the following 3 methods. 1)public boolean hasNext(); 2)public Obect next() 3)public void remove(); import java.util.*; class IteratorDemo { public static void main(String[]args) { ArrayList l=new ArrayList(); for(int i=0;i<=10;i++) { l.add(i); } S.O.P(l); o/p[0,1,2,3........10] Iterator itr=l.iterator(); while(itr.hasNext())
  • 11.
    { Integer I= (Integer)itr.next(); If(I%2==0) { S.O.P(I); } else { Itr.remove(); } } S.O.P(l);o/p[0,2,4,6,8] } Limitations of Iterator: In the case of iterator and enumeration we can always move towards the forwards direction we can’t move backward direction i.e these cursors are single direction cursors but not bidirectional.we can’t perform replacement and edition of new objects. To solve this problem SUN people introduced ListIterator in 1.2 version. ListIterator:- Iterator we can move either to forward or to the backword direction . i,e ListIterator is Bidirectional cursor. in addition to read remove operations. ator ListIterator object by using ListIterator of List interface Methods: 1)public boolean hasNext() 2)public Object next()
  • 12.
    3)public int nextIndex() 4)publicboolean hasPrevious() 5)public Object previous() 6)public int previousIndex() 7)public void remove() 8)public void set(Object new) 9)public void add(Object new) import java.util.*; class ListIteratorDemo { Public static void main(String []args) { LinkedList l=new LinkedList(); l.add(“pavan”); l.add(“chiru”); l.add(“venky”); l.add(“arjune”); l.add(“nag”); S.O.P(l); ListIterator ltr=l.listIterator(); while(ltr.hasNext()) { String s=(String)ltr.next(); If(s.equals(“venky”)) Ltr.remove(); If(s.equals(“chiru”))
  • 13.
    Ltr.set(“charan”); If(s.equals(“nag”)) Ltr.add(“chaitanya”); } S.O.P(l); } } Set(CC)  Setis childinterfaceof Collection.  If we wantto representagroupof objectswhere duplicatesare notallowedandinsertion orderis notpreservedthenwe shouldgoforSet.  HashSet(CC):-  The underlyingdatastructure isHashtable  Duplicate objectsare not allowed.  If we are tryingto add duplicate objectswe won’tgetanyerroradd() simplyreturnsfalse  Heterogeneousobjectsare allowed  Null insertionispossible (onlyonce) becauseduplicatesare notallowed  HashsetimplementsSerializable andClonable interfaces Constructor  HashSeth=newHashSet();  Createsan emptyHashSetobectswithdefaultintial capacity16 anddefaultfillratio 0.75(75%)  HashSeth=newHashSet(intinitcapacity);  Createsan emptyHashSetobectswiththe specified intialcapacityand defaultfillratio 0.75(75%)  HashSeth=newHashSet(intinitcapacity,floatfillratio)  HashSeth=newHashSet(Collectionc)
  • 14.
    import java.util.*; class HashSetDemo { HashSeth=new HashSet(); h.add(“B”); h.add(“C”); h.add(“D”); h.add(“Z”); h.add(“null”); h.add(10); S.O.P(h.add(“Z”)); o/p false S.O.P(b); o/p[null ,D,B,C,10,Z] } } note : insertion order is not preserved SortedSet(I): we shouldgofor SortedSet. 1)Objectfirst() Returnsthe firstelementof SortedSet. 2)Objectlast() Returnsthe firstelementof SortedSet. 3)SortedSetheadSet(Objectobj) Returnsthe SoredSetwhose elementsare lessthanobj 4)SortedSettailSet(Objectobj)
  • 15.
    Returnsthe SoredSetwhose elementsaregraterthanare equal toobj 5)SortedSetsubSet(Objectobj1,Objectobj2) Returnsthe SoredSetwhose elementsare >= to obj1 and<obj2 6)Comparatorcomparator()  If we use defaultnatural sortingorderthenwe will getnull  Eg: [100,101,103,104,107,109] first() returns100 last() returns109 headset(104) returns[100,101,103] tailSet(104) returns[104,107,109] subset(101,107) returns[101,103,104] Comparator() returnsnull Note: TreeSet(c) Exceptionandnull insertion isnot possible Constructors: TreeSett=newTreeSet(); TreeSett=newTreeSet(Comparatorc) createsan emptyTreeSetobjectwhere sortingorderis cunstomizedsortingorderspecifiedby Comparatorobject.
  • 16.
    TreeSett=newTreeSet(Collectionc) TreeSett=newTreeSet(SortedSetc) importjava.util.*; classTreeSetDemo { P S Vmain(String[]args) { TreeSett=newTreeSet(); t.add(“A”); t.add(“a”); t.add(“B”); t.add(“Z”); t.add(“L”); //t.add(new Integer(10));//CCEClassCastException S.O.P(t);[A,B,L,Z,a] } } null acceptance:- -emptyTreeSetif we are tryingto insertnull we will getNullPointerException TreeSetaddthe firstelementnullinsertionisalwayspossible. Importjava.util.*; ClassTreeSetDemo { Publicstaticvoidmain(String[]args)
  • 17.
    { TreeSett=newTreeSet(); t.add(newStringBuffer(“A”)); t.add(newStringBuffer(“Z”)); t.add(newStringBuffer(“L”)); t.add(newStringBuffer(“B”)); } } o/pCCE comparable otherwisewe willgetClassCastException. interface. implementscomparableinterface .henceinthe above example we gotCCE. Comparable Interface:- PublicintcompareTo(Objectobj) Obj1.comapreTo(obj2) –ve if obj1 has to come before obj2 returns+ve if obj1 has to come afterobj2 importjava.util.*; classTest { P S V M(String[]args) { S.O.P(“A”.compareTo(”Z”));// -ve =>-25 S.O.P(“K”.compareTo(”A”));//+ve =>15
  • 18.
    S.O.P(“A”.compareTo(”A”));//0 } } whenwe are dependingondefaultnaturalsortingorderinternallyJVMcallscomareTo() –type JVMindetifiesthe locationof the elementinsortingorder obj1.compareTo(obj2) ctinTreeSet –ve if obj1 has to come before obj2 Treesett=newTreeSet(); t.add(“Z”); -ve -ve -->+ve -ve //t.add(null);//NPE } o/p[D,K,M,Z] if we are not satisfiedwithdefaultnatural sortingorder(or) if the defaultsortingorderisnot available thenwe candefine ourowncustomizedsortingbyusingcomparator. Comparator(I) s. 1) Publicintcompare(objectobj1,Objectobj2)
  • 19.
    –ve if obj1has to come before obj2 2)publicbooleanequals(Objectobj) implementationforcompare() ,2nd methodequals() implementationisoptional because itis alreadyavailable forourclassformobjectclassthrough interface. Importjava.util.*; classTreeSetDemo3 { P S V M(String[]args) { t .ad(20); t .add(0); ------- t.add(15);------ ------- -ve t.add(5); ---- -ve t.add(10)---- -ve S .O.P(t);
  • 20.
    } } classMyComparator implementsComparator { P intcompare(Objectobj1,Objectobj2) { IntegerI1=(Interger)obj1; Integeri2=(Integer)obj2; If(I1<I2) return+100; elseif(I1>I2) return-1000; else return0; } } mentfor defaultnatural sortingorder.inthiscase the o/pis[0,5,10,15,20] ismentfor customizedsortingorder.these case the o/pis [20,15,10,5,0] Various alternatives of implementing compare():- ClassMyComparatorimplementsComparator { P S V main(String[]args) { IntergerI1=(Integer)obj1; IntergerI2=(Integer)obj2;
  • 21.
    //return - //return - //return- } } tingorderisreverse of alphabetical order? importjava.util.*; classTreesetDemo2 { TreeSett=newTreeSet(newMyComparator()) t.add(“A”); t.add(“Z”); t.add(“k”); t.add(“B”); t.add(“a”); S.O.P(t); } } ClassMyComparatorimplementsComparator { publicintcompare(Objectobj1,Objectobj2) { Strings1=(String)obj1; Strings2=obj2.toString();
  • 22.
    returns–s1.compareTo(s2); } } Note:InObjectsand StringBufferthere isnocompareTo(),sowe have toConvertStringBuffer intoString. W A P to insertStringand StringBufferobjectsintothe TreeSetwhere the Sortingorder increasinglengthorder.If twoobjectshavingthe same lengththenconsidertheiralphabetical order. Importjava.util.*; classTreeSetDemo { TreeSett=newTreeSet(newMyComparator()); t.add(“A”); t.add(newStringBuffer(“ABC”)); t.add(newStringBuffer(“AA”)); t.add(“XX”); t.add(“ABCD”); t.add(“A”); S.O.P(t);o/p[A,AA,XX,ABC,ABCD] } } ClassMyComparatorimplementsComparator { Publicintcompare(Objectobj1,Objectobj2) { Strings1=obj1.toString(); Strings2=obj2.toString(); intl1=s1.length(); intl2=s2.length();
  • 23.
    if(l1<l2) return-1; else if(l1>l2) return1; else returns1.compareTo(s2); } } W AP to insertStringBufferobjectsintothe TreeSetwhere the sortingorderlsalphabetical order? importjava.util.*; P S V M(String[]args) { TreeSett=newTreeSet(newMyComparator()); t.add(newStringBuffer(“A”); t.add(newStringBuffer(“Z”); t.add(newStringBuffer(“K”); t.add(newStringBuffer(“L”); S.O.P(t); [A,K,L,Z] } } classMyComparator implementsComparator { Strings1=obj1.toString(); Strings2=obj2.toString(); returns1.compareTo(s2); } }
  • 24.
    Map(I):- -->if we wanttorepresentagroupof objectsaskey-value pairsthenwe shouldgoforMap.Both key& valuesare objects. esare objects -value pairiscalledEntry. Rollno name 101 satya key 102 srinu Entry 103 ravi value 104 krishna 105 gagan there isnorelationshipb/wCollectionandMap. -value pairs. 1) Objectput(Objectkey,Objectvalue) o addkey-value pairtothe map value will be returned. 2) VoidputAll(Objectkey) -value pairs 3) Objectget(Objectkey) ociatedwithspecifiedkey 4) Objectremove(Objectkey)
  • 25.
    5) booleancontainsKey(Objectkey) 6) booleancontainsValue(Objectvalue) 7)intsize() 8) voidclear() 9) booleanisEmpty() 10) SetkeySet() 11) Collectionvalues() 12) SetentrySet() Entry(I) -valuepairiscalledone Entry. Hence ,interface Entryisdefine insideMapInterface. interface Map { Interface Entry { ObjectgetKey() ObjectgetValue() ObjectsetValue() } } HashMap:- -->the underlyingdatastructure isHashTable hCode of keys
  • 26.
    Constructor:- HashMap m=newHashMap() 0.75(75%) ashMap(intinitialcapacity) importjava.util.*; classHashMapDemo { HashMap m=newHashMap(); m.put(“chiru”,700); m.put(“balaiah”,800); m.put(“venkatesh”,1000); m.put(“nagarjuna”,500); S.O.P(m);{venkatesh=1000,balaiah=800,chiru=700,nagajuna=500} S.O.P(m.put(“chiru”,1000));o/p700 Sets=m.keySet(); S.O.P(s); [venkatesh,balaiah,chiru,nagarjuna] Collectionc=m.values(); S.O.P(c);[1000,800,1000,500] Sets1=m.entrySet(); While(its.hasNext()) { Map.Entry m1=(Map.Entry)its.next(); S.O.P(m1.getKey()+”.......”+m1.getValues()); If(m1.getKey().equals(“nagarjuna”))
  • 27.
    m1.setValue(10000); } S.O.P(m); } } } } LinkedHashMap:- same as HashMapexceptthe followingdifferences HashMap LinkedList 1)the underlyingD.SisHashTable HashTable+LinkedList 2)insertionorderisnotpreserved preserved 3)introducedin1.2 version 1.4 version e replacingHashMap withLinkedHashMapthe followingisthe O/P {chiru=700 ,balaiah=800,venkatesh=1000,nagajuna=500} Insertionorderispreserved.