Java - Collection Framework - Durga Soft
Java - Collection Framework - Durga Soft
Need Of Collections
An array is an indexed Collection of fixed number of homogeneous data elements.
The Main advantage of Arrays is we can represent multiple values with a single variable.
So that reusability of the code will be improved.
Arrays Concept is not implemented based on some standard data structure hence readymade method support is not available
for every requirement we have to write the code explicitly. Which is complexity of progra
RGASOET
<br>
Need Of Collections
To overcome the above limitations of Arrays we should go for Collections.
Collections are growbable in nature. i.e. Based on our requirement we can increase (or) Decrease the size.
Collections can hold both homogeneous & Heterogeneous elements.
Every Collection class is implemented based on some standard data structure. Hence readymade method support is
available for every requirement. Being a programmer we have to use this method and we are not responsible to provide
implementation.
DURGASOFT
<br>
Arrays Collections
1. Arrays are fixed in size. 1. Collections are growable in nature. I.e.
based on our requirement we can
increase or decrease the size.
2. Wrt memory arrays are not 2. Wrt to memory collections are
recommended to use. recommended to use.
3. Wt Performance Arays are 3. Wrt Performance collections are not
recommended to use. recommended to use.
4. Array can hold only homogeneous 4. Collections can hold both homogeneous
datatype elements and heterogeneous elements.
5. There is no underlying data structure for 5. Every Collections class is implemented
arrays and hence readymade method based on some standard data structure.
support is not available Hence readymade method support is
available for every requirement.
6. Array can hold both primitives and 6. Collections can hold only objects but
object types not primitives.
DURGASOET
<br>
Java C++
Collection Container
DURGAS
<br>
DURGASOFT
<br>
What is Collection?
What is Collection?
Java C++
Collection Container
DURGASOET
<br>
Note: Vector and Stack classes are re-engineer in 1.2v to implement list interface
<br>
DURGASOFT
<br>
List Set
* Duplicates are allowed * Duplicates are not allowed
* Insertion order preserved * Insertion order not preserved
DURGASOFT
<br>
iv. SortedSet:
* Iit
is the child interface of Set.
* If we want to represent a group of individual objects as a
single entity where duplicates are not allowed but all objects
should be inserted according to some sorting orde then we
should go for SortedSet.
DURGASOET
<br>
v. NavigableSet:
* It is the child
interface of SortedSet if defines
several methods for navigation purposes.
J
<br>
o
NavigableSet (1.6 version)
DURGASOFT
<br>
vi. Queue :
* It is child interface of Collection.
want to represent a group of individual objects prior to
* If we
Ex: befor9 sending a mail all mil id's we have to store somewhere and
in which order we saved in the same order mail's should be delivered
(First in Fist out) for this requiremsnt Qusus concspt is the best choice.
DURGASOFT
<br>
LinkedBlocking Queue
(1.5 version)
PriorityBlockingQueue
(1.5 version)
<br>
DURGASOFT
<br>
Dictionary
(1.0 version)
LinkedHashMap Properties
(1.0 version)
(1.4 version)
DURGASOFT
<br>
viii. SortedMap:
* It is the child interface of map.
If we want torepresent a group of key value pairs
according to some sortingorder of keys then we should
go for SortedMap
Map ) (12 version)
DURGASOFT
<br>
ix.NavigableMap:
SortedMap Q
2 verslon)
o (t8 verslon)
NavigableMap
TreeMap 12 veralon),
DURGASOFT
<br>
Collection ()
(1.2)
List ()
Set () Queue ()
(L21)
(12v) (1.5V)
PrlorityBlockingQueue
LinkedHashSet Navigableset ()
Stack (15v)
(1.00) (L4V) (1.6v)
LinkedBlocingQueue
Legacy Classes
(15v)
TreeSet
(1.2v)
DURGASOFT
<br>
Collection Interface
Note:
Collection interface doesn't contain any method to retrieve objects there
is no concrete class which implements collection class directly.
<br>
:
List Interface
* It is the child interface of Collection.
* If we want to represent a group of individual objects as a
single entity where duplicates are allowed and insertion order
must be preserved then we should go for List.
*We can dferentiate duplicates by using index.
* We can preserve insertion order by using index, hence index
play very important role in list interface.
DURGASOFT
<br>
ArrayList
ArrayList Constructors
ArrayList Constructors
Ladd(A"); Ladd('N";
System.out.prindn(): # A, 10, M, nul,N
<br>
ArrayList
ArrayList
RandomÁCcess
ndsOFT
<br>
Non-Synchronized
ArrayList 11=new ArrayList 0;
Synchronized
List I-Collections.synchronizedList (I1l);
<br>
LinkedList
LinkedList
* LinkedList implements Serializable and Clonable interfaces
but not RandomAccess interface.
LinkedList
*Usually we can use LinkedList to implement stacks and queues to
provide support for this requirement LinkedList cass defines following
specific methods.
void addFirst();
void addLast();
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();
DURGASOFT
<br>
LinkedList Constructors
DURGASOFT
<br>
DURGASOFT
<br>
It is the best choice if our frequent Itisthe best choice if our frequent
operation is retrieval Operation is insertion and deletion
ArrayList is the worst choice if our LinkedList is the worst choice if our
frequent operation is insertion or frequent operation is retrieval
deletion operation
Underlying data structure for Underlying data structure is Double
ArrayList is resizable or growable Linked List.
Array.
ArrayList implements LinkedList doesn't implement
RandomAccess interface RandomACcess interface
DUNFOOFT
<br>
Vector
*The undertlying Data structure for thevector is resizable aray or growable aray.
*
Duplicate objects are allowed.
* Inserion order is preserved.
"null'inserion is possible.
Vector specificmethods
DURGASOFT
<br>
DURGASOFT
<br>
Other Methods:
int size();
int capacity ();
Enumeration elements ();
DURGASOFT
<br>
DURGASOFT
<br>
Stack
DURGASOFT
<br>
Constructor of Stack
DURGASOFT
<br>
Methods in Stack
1) Object push(Object obj:
-
For inserting an object to the stack
2) Objectpop:
-
To removes and returns top of the stack.
3) Object peak):
-
To Returns the top of the stack without removalof object.
4) int search(Object ob);:
- If
the specified object is available it returns its offset from top of the stack.
- If
the object is not available then it returns -1.
5) Object pop0;
-For inserting an object to the stack DURGASOFT
<br>
import java.util.*;
class StackDemo{
public static void main (String arg[l) {
DURGASOFT
<br>
* Enumeration
* Iterator
*
Listlterator
DURGASOFT
<br>
Enumeration
* Introduced in 1.0 version(for Legacy).
*We can use Enumeration to get Objects one by one from the
old Collecion Objects(Legacy Collecions).
DURGASOFT
<br>
Method of Enumeration
DURGASOFT
<br>
import java.util.*;
class EnumaretionDemo1{
Enumeration e v.elements ();
=
public static void main(String arg[]) {
DURGASOFT
<br>
Enumeration
Limitations of Enumeration:
Iterator
1. We can apply lterator concept for any Collection object
hence it is universal cursor.
DURGASOFT
<br>
Iterator
* We can create Iterator object by using iterator () method of
Collection interface.
public Iterator iterator ();
Example:
Iterator itr-C. iterator0;
* where C is any Collection Object
DURGASOFT
<br>
Methods in Iterator
DURGASO
<br>
import java.util.*;
class IteratorDemo {
public static void main(Stringl args) { Iterator itr =.iterator ();
While (itr.hasNext ()){
ArrayList l=new ArrayList();
Integer n= (Integer) itr.next ();
for(int i=0;i<10;i++) {
I. add ();
if (n%2==0)
System.out.println (n); / 0
24 6 8
System.out.println (); /[0,1,2,------10]
System.out.println (); /[0,1,2,3,4...10]
DURGASOFT
<br>
Limitations of Iterator
1.By using Enumeration and Iterator we can move only towards forward direcion
and we can't move to the backward direction, and hence these are single
direction cursors.
2. By usingIteratorwe can perfom only read and remoOve operations and we can't
perform replacement of new Objects.
DURGASOFT
<br>
Listlterator
1. By using Listlterator we can move either to the forward
direction or to the backward direction, and hence
Listlterator is bidirectional cursor.
Listlterator
*We can create Listlterator Object by using listlterator )
methodof List Interface.
public Listlterator listlterator ()
Example:
Listterator itr-. listiterator (0:
* where lis any List Object
DURGASOFT
<br>
Methods in Listlterator
* Listlterator is the child interface of Iterator and hence allmethods of lterator by
default available to Listlterator.
* Listiterator Interface defines the following9methods
System.out.println ();
II[balakrishna, charan,nag, chaitu]
}} DURGASOFT
<br>
Listlterator
universal cursor.
DURGASOFT
<br>
Movement Only forward Only forward Both forward and backward direction(bi
directio n(single direction) directio n(single directio nal)
direction)
Accessibility Only read access Both read and remove Read ,remove, replace and addition of
new objects
How to get it? Byusing elements() By using iterator() By using listIterator() method of List
method of Vector class method of Collection interface
interface
DURGASOFT
<br>
DURGASOFT
<br>
Set Interface :
Collection (1.2 version)
Set
1. Set is the child interface of Collection.
HashSet
*The underlying data structure is Hashtable.
Duplicates are not allowed. If we are trying to insert duplicates, we won't
get any compiletime or runtime errors. add) method simply retums false.
*Insertion order is not preserved and all objects willbe inserted based on
hash-code of objects.
* Heterogeneous objects are allowed.
*' null ' inserion is possible.
implements Serializable and Clonable interfaces but not RandomAccess.
* HashSet is the best choice, if our frequent operation is Search operation.
DURGASOFT
<br>
Constructorsof HashSet
1) HashSet h = new HashSet();
-Creates an empty HashSet object with default initial capacity 16
& default Fill Retio 0.75
2) HashSet h = new HashSet(int initalCapacity):
-
Creates an empty HashSet object with specified initial capacity
& default Fill Retio 0.75
Constructors of HashSet
:
Load Factor / Fill Ratio
-After loading the how much factor, a new HashSet object
will be created, that factor is called as Load Factor or Fill Ratio.
DURGASOFT
<br>
LinkedHashSet
It is the child class of HashSet.
* Introduced in 1.4 version.
It is exaciy same as HashSet except the following diferences.
HashSet LinkedHashSet
The underlying datastructure is The underlying datastructure is
Hash table. Hash table + Linked List.
(that is hybrid data structure)
BURGASOFT
<br>
LinkedHashSet
Note:
-
LinkedHashSet is the bestchoice to develop cache based
applications, where duplicates are not allowed and insertion
order must be preserved.
DURGASOFT
<br>
SortedSet (I)
SortsdSet headSet(Object objD - retums the SortedSet whose elements are <obj
- retums
SortedSet tallSet(Objoct obj) the SortedSet whose elements are >= obj
SortedSet subSetObject obj1, Object obj2)
- returms the SortedSet whose elements are >= obj1 and <obj2
Comparator comparator)
-returms Comparator object that describes undertying sortäng technique.
If we are using default natural soräing order hen we will get null.
<br>
Example : {100,101,103,104,107,110,115}
1. first() ->
100
->
2. last()
3. headset(104)
4. tailSet(104)
-115
(100,101,103]
-> [104,107,110,115]
5. subset(103,110) -> [103,104,107)
6. comparator) null
Note:
1. Default natural soringorder for numbers Ascending onder and
for String alphabeical order.
2. We can apply he above methods only on SortedSet implemented class
objecis. That is on the TrseSet object.
<br>
TreeSet
1. The underlying data structure for TreeSet is Balanced Tree.
2. Duplicate objects are not allowed.
3. Insertion order not preserved, but allobjecis will be inserted according
to some sorting order.
4. Heterogeneous objects are not allowed. If we are trying to insert
heterogeneous objects then we will get runtime exception saying
ClassCastException.
5. Null Insertion is allowed, but only once.
<br>
TreeSet Constructors
1. TreeSet t-new TreeSet);
Creates an empty TreeSet object where elements willbe inserted acoording to
default natural soring order.
Null Acceptance
2. For Non empty TreeSet If we are trying to insert Nul then we willget
NullPointerExcpetion.
<br>
Example
import java.util. TreeSet;
class TreeSetDemo1{
public static void main(String] args) {
TreeSet new TreeSet():
t=
tadd(new StringBuffer('A)%
tadd(new StingBuffer(Z');
tadd(new StringBufer(L"));
tadd(new StringBuffer(B");
System.outprintn(t); l ClassCastException
}
<br>
:
Note
1. If we are depending on default natural sorting order then objects
should be homogeneous and comparable. Otherwise we willget
runtime exception saying ClassCastException.
2. Anobject is Said to be comparable if and only if the coTesponding
class implements java.lang.comparable inteface.
3. String Class and allwrapper classes already implements comparable
interface. But StringBuffer doesn't implement comparable interface.
Comparable Interface:
This interface present in java.lang package it contains only one
method CompareTo().
public int CompareTo(Object obj)
Example :
obj1.Compare To(obj2)
retums -ve iff obj1 has to come before obj2
>
retums *ve ii obj1 has to come after obj2
retums Oif obj1 &obj2 are equal.
<br>
Example
class Test{
public static void main(String[]| angs) {
System.out,printn('A".compareTo((Z"); -ve
l
System.ouLprintin(Z".compareTo(B"); /ve
System.out.printin('A".compareTo(A"); W0
/
System.out. prindn(A".compare To(null); NullPointerException
}
}
<br>
Note:
1. If we arenot satisfied with default natural sorting order or if the
default natural sortingorder is not already available then we can
define our own customized sorting by using Comparator.
Comparator Interface
DURGASOFT
<br>
Write A Program to insert integer objects into the TreeSet where the sorting order
isdescending order:
import java.uil.";
class TreeSetDemo3 { cdass MyComparator implements Comparator {
public static void main(Süring[] args) { public int compare(Objsct obji, Objsct cbj2){
TreeSet ts new TreeSetnewMyComparatorO);–ine1 Integer I1=(integer)obj1;
Ladd(10); Integer i2-(lnteger)obj2;
tadd(0); 1<12)
Ladd(15); retum +1;
Ladd(20);* else if(|1>12)
Ladd(20); retum -1;
System.out.prindn(t); else
retum 0;
}
Output: [20,15,10,0]
DURGASOFT
<br>
tadd(20);
tadd(20);
-ve
-Ve
Compars20,10):
Compars(20,15);
tadd(20); vecompare(20,10);
t.add(20); ve cOmpars (20,15;
tadd(20); - Gompars (20,20):
; M
System.out.prindn() 20,15,10,0]
DURGASOFT
<br>
*At line-1 if we are not passing comparator object then intermally JVM
will call CompareTo( method which meant for default natural sorting
order (ascending order).
Inthis case output is [0,10,15,20].
* lf weare passing comparator object at line1 then intermally JVM will
callcompare) method which is meant for customized sorting.
(Descending order).
In this case output is (20,15,10,0]
DURGASOF
<br>
DURGASOFT
<br>
Write a program to insert String objects into the TreeSet where sorting order is
Reverse of Alphabetical order:
import java.util.;
class TreeSetDemo2 {
public staic void main(Süring] args) {
TreeSet t= nw TreeSelnew MyConmparator);
tadd("Roja');
tadd"ShobhaRanl" } class MyComparator implements Comparator {
Lado("RajaKumari'; pubic intcompara(Objsct obj1, Objsct abj2) {
taddGangaBhavanl; Sring s1 = obj1.oSring0:
tadd("Ramulamma"'; Sting s2 =(Sting)obj2:
System.out.prindn(); Il rstum s2.comparelo(s1);
retum -s1.compareTo(s2);
}
}
Write a program to insert StringBuffer objects into the TreeSet where sorting
order is Alphabetical order:
import java.uil.";
class TreeSetDemo10 {
public staic void msin(Süring] args) {
TreeSat t= naw TresSsi(new MyComparator);
tadd(new SiringBufierA);
taddl(new StringBuffer(");
dass MyComparator implements Comparator {
taddl(new StringBufierK; public int compare(Objecd obj1, Object obj2) {
tadd(new Sting Bufiler"L); String = obj1.toString0:
si
System.out.prndün();
String s2 = obj2.00String0:
retum s1.compare To(s2);
}
Output: A, K, L, Z]
DURGASOFT
<br>
:
Note
* If we are
defining our own sorting by Comparator, the objects
need not be Comparable.
DURGASOFT
<br>
Write a program to insert String and StringBuffer objects intothe TreeSet where sorting order is
increasing length order if two objects having the same length then consider their alphabetical order?
import java.util.;
class MyComparator implements Comparator {
dlass TreeSetDemo12 {
publc int compar(Object obj1, Object obj2){
public staic voId main(String ] args) (
Sring si = obji .toString0:
TreeSet t= NEw TreeSetnewMyComparator)):
Sring s2 = obj2.toString0:;
Ladd'A; int I1=s1.length():
tadi(new String Buffer ABG); int 12-s2.length:
Laddl(new SiingBufer(AA);
i(1<2)
reum -1;
tadd ABCD; else ifl1>12)
tadd(A'; returm 1;
System.outprindn();
else
retum s1.compare To(s2);
}
Note :
1.If we are
depending on default natural soring order hen objects
should be homogeneOUs and comparable otherwise we willget
runtime exCeption saying ClassCastException.
DURGASOFT
<br>
DURGASOFT
<br>
The
DURGASOFT
<br>
import java.util.;
dass Employee implensnts Comparable { public int compareTo(Object cb) {
String name; int eid1 = this.eid;
int eid; Employse e=(Employee)obj;
Employee(String name, int eid) { int eid2 = e.eid;
this.name = name; if(eid1< eid2){
this.eid = eid; return -1;
} }else if (eid1> eid2){
public String toString() { retum 1;
retum name+"-"+eid; }else{
retum 0;
<br>
class CompCompDemo{
public staticvoid main(Sringl] args) {
Employee el = new Employee(nag', 100);
new Employee('balaiah 200);
Employse 2=
Employee e3 = newEmployee(chiru", 50);
Employsa e4= new Employse(venk", 150);
Employse e5 = nsw Employee(nag,100) TreeSet s new TreeSetnew MyComparator0;
ti
TreeSet t = new TreeSet):
1.add(e1);
Ladd(e1); t1.add(e2);
tadd(e2); t1.add(e3);
tadd(a3); t1.add(e4),
tadd(e4); t1.add(s5);
Ladd(e5);
System.out.prindn(t1);
Syotem.out prindin(0:
<br>
Comparable Comparator
1. Itis meant for default natural sorting order. 1. Itis meant for customized sorting order.
4. All wrapper classes and String class implement comparable 4. The only implemented classes of Comparator are Collator and
interface. RuleBasedCollator.
DURGASOFT
<br>
6. Null Acceptance Allowed (only once) Allowed(only once) For Empty Tree Set as first element
Null is allowed and in all other cases
we will get NullPointerException
DURGASOFT