0% found this document useful (0 votes)
3 views

Java - Collection Framework - Durga Soft

The document discusses the need for collections in programming, highlighting their advantages over arrays, such as dynamic sizing and the ability to hold heterogeneous data. It outlines the key interfaces of the Collection Framework in Java, including Collection, List, Set, and Map, and their specific characteristics. Additionally, it compares ArrayList and Vector, emphasizing performance differences and synchronization options.

Uploaded by

umkofficial536
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java - Collection Framework - Durga Soft

The document discusses the need for collections in programming, highlighting their advantages over arrays, such as dynamic sizing and the ability to hold heterogeneous data. It outlines the key interfaces of the Collection Framework in Java, including Collection, List, Set, and Map, and their specific characteristics. Additionally, it compares ArrayList and Vector, emphasizing performance differences and synchronization options.

Uploaded by

umkofficial536
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 115

<br>

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.

Limitations of Object type Arrays:


Arrays are fixed in size i.e. once we created an array with some size there is no chance of increasing or decreasing it's size based on
our requirement. Hence to use arrays compulsory we should know the size in advance which may not possible always.

2) Arrays can hold only homogeneous data elements.


Ex:
Student [] s= new Student [10000]:
s[0] = new Student; (correct)
s[1] = new Customer(): (wrong)

But We can resolve this problem by using object Arrays.


Object [] o = new Object [100001;
o[0] = new Student(0:
o[1] = new Customer():

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>

Difference between Arrays and Collections:

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

Collection Framework STL (Standard Template Library)

DURGAS
<br>

What is Collection Framework?

It defines several classes and interfaces which can be used


a group of objects as single entity.

DURGASOFT
<br>

What is Collection?

as Sialle,eeity Uhe ue should go0rcollecdon.


<br>

What is Collection?

If we want to represent a group of individual objects


as a single entity then we should go for Collection.

What is Collection Framework?

It defines several classes and interfaces which can be used


a group of objects as single entity.

Java C++

Collection Container

Collection Framework STL (Standard Template Library)


<br>

9-Key Interfaces of Collection Framework


i. Collection :

* If we want to represent a group of individual objects as a


single entity then we should go for Collection.
* Collection interface defines the most common methods
which are applicable for any Collection object.
* In general collection interface is considered as root
interface of Collection Framework.
Note: there is no concrete class which implements collection
interface directly.
DIRGASOET
<br>

Difference between Collection & Collections

*Collection is an interface which can be used to represent


a group of individual objects as a single entity.

*Collections is an utility class present injava.util.package


to define several uility methods (like Sorting, Searching..)
for Collection objects.

DURGASOET
<br>

9 key interfaces of Collection Framework


ii. List :

* List is 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
preserved then we should go for List.
<br>

9 key interfaces of Collection Framework


ii. List :
Collection
(1.2 version)

List (1.2 version)

ArrayList Linked List Vector (10 version)


(1.2 version) (1.2 version)

Stack (1.0 version)

Note: Vector and Stack classes are re-engineer in 1.2v to implement list interface
<br>

9 key interfaces of Collection Framework


iii. Set:

* It is the child interface of Collecion.


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

DURGASOFT
<br>

9 key interfaces of Collection Framework


:
iii. Set Collection (12version)

Set (1.2 version)

HashSet (12 version)

LinkedHashSet 1.4 version)


IRGASOFT
<br>

Difference between List & Set

List Set
* Duplicates are allowed * Duplicates are not allowed
* Insertion order preserved * Insertion order not preserved

DURGASOFT
<br>

9 key interfaces of Collection Framework

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>

9 key interfaces of Collection Framework

v. NavigableSet:

* It is the child
interface of SortedSet if defines
several methods for navigation purposes.

J
<br>

9 key interfaces of Collection Framework


Collection )0.2 verslon)

Set () (1.2 version)

SortedSet o 1.2 version)

o
NavigableSet (1.6 version)

TreeSet (n2 version)

DURGASOFT
<br>

9 key interfaces of Collection Framework

vi. Queue :
* It is child interface of Collection.
want to represent a group of individual objects prior to
* If we

processing then we should go for Queue.

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>

9 key interfaces of Collection Framework


vi. Queue : Collection ) (1.2 version)

Queue ) (1.5 version)

PriorityQueue BlockingQueue (1.5 version)


(1.5 version)

LinkedBlocking Queue
(1.5 version)

PriorityBlockingQueue
(1.5 version)
<br>

9 key interfaces of Collection Framework


Note:
*All theabove interfaces
(Collecion, List, Set, SortedSet, NavigableSet and Queue)
meant for representing a group of individual objects.
represent a group of objects as key value pairs
*lIf we want to

then we should go for Map Interface.

DURGASOFT
<br>

9 key interfaces of Collection Framework


vii. Map:
* Map is not the child interface of Collection.
If we want to represent a group of individual objects as
key value pairs then should go for Map.
Ex: Roll No Name
101 Durga
102 Ravi
103 Venkat
Both key and value are objects, duplicated keys are not
allowed but values can be duplicated
<br>

9 key interfaces of Collection Framework


o
vii. Map: Map (1.2 version)

Dictionary
(1.0 version)

HashMap WeakHashMap IdentityHashMap Hashtable


(1.2 version) (1.2 version) (1.0 version)
(1.4 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)

SortedMap o (1.2 version)

DURGASOFT
<br>

ix.NavigableMap:

*It is the child interface of sorted map, it defines several


utlity methods for navigation purpose.
Map o
(1.2 version)

SortedMap Q
2 verslon)

o (t8 verslon)
NavigableMap

TreeMap 12 veralon),
DURGASOFT
<br>

Collection ()
(1.2)

List ()
Set () Queue ()
(L21)
(12v) (1.5V)

LUnkedist HashSet Sortedset () PriorityQueue () BlockdngQueue


Arrayist Vector (1.5v)
(12V] (12V) (12V) (15v)
(12) (1.00)

PrlorityBlockingQueue
LinkedHashSet Navigableset ()
Stack (15v)
(1.00) (L4V) (1.6v)

LinkedBlocingQueue
Legacy Classes
(15v)
TreeSet
(1.2v)

DURGASOFT
<br>

Important methods of Collection Interface

boolean add(Object o) boolean contains(Object o)


boolean addAll(Collection c) boolean containsAll(Cllecion c)
boolean remove(Objecto) boolean isEmpty()
boolean removeAl(Collection c) int size()
boolean retainAl(Collection c) object] toAray()
void clear() Iterator iterator()
<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>

List interface specific methods


void add(irnt index, Object o)
boolean addAll(int index, Colleclion c)
object get(int index)
object remove(int index)
object set(int index, Object new)
int indexOf(Object o)
int lastlndexOf(0bject o)
Listlterator listiterator():
DURGASOFT
<br>

ArrayList

The underlined data structure Resizable Aray or Growable Array


Duplicates are allowed.
• Insertion order is preserved.
• Heterogeneous objects are allowed [except TreeSet & TreeMap
everywhere heterogeneous objects are allowed].
Null insertion is possilble.
<br>

ArrayList Constructors

1. ArrayList al = new ArayList)


Creates an empty Array list object with defauit initial capacity 10.
Once Array List reaches its map capacity a new Aray List will be
created with new capacity = (Currentcapacity * 32) + 1.
<br>

ArrayList Constructors

2.AmayList al = new AayList(int initialCapacity);

3.AayList al = new ArayList(Collection c);


<br>

Example for ArrayList


import java.udil.*;
Class ArayListDemo { Ladd(null);
public staic void main(Sring] args) (
ArayList |= now ArayLisi);
System.out.prinün(); IA, 10,A, nul]
I.ramove(2);
Ladd('A")
Ladd(10);
System.out.prndn():
l.add(2, m;
/ [A, 10, nul

Ladd(A"); Ladd('N";
System.out.prindn(): # A, 10, M, nul,N
<br>

*Usually we can use Collections to hold and transfer Objects


from one place to another place, to provide support for this
requirement every Collection already implements
Serializable and Cloneable interfaces.
<br>

*ArayList and Vector classes implements RandomAccess


interface so that we can access any Random element with
the same speed.

Hence if our frequent operation is retrieval operation then


ArayList is the best choice.
<br>

ArrayList

ArrayList l1-new ArayList ();


LinkedList I2-new LinkedList (0;
System.out-printtn (11 instanceOf Serializable); I/rue
System.out.println (12 instanceOf Cloneable); Itrue
System.out.printn (11 instanceOf RandomAccess); lirue
System.out.printin (12 instanceOf RandomAccess); Iifalse
<br>

ArrayList

*ArayList is best choice if our frequent operation is retrieval operation


(Because AayList implements RandomAccess interfaces)

*ArayList is the worst choice if our frequent operation is inserion or


deletion in the middle (Because several shift operation are require)
<br>

RandomÁCcess

*Present in java.util package.

*It doesnt contain any methods and it isa Marker interface


<br>

Difference between rrayList & Vector


ArrayList Vector
Every method present Arraylist is Every method present in
non synchronize | LinkedList synchronize
is
At a time multiple threads are |At time only one thread is
a

allowed to operate on Arraylist allowed to operate on Vector


Object and hence Arraylist is not Object is thread safe
thread safe
Threads are not required to wait Threads are required to wait to
to operate on Arraylist, hence operate on Vector Object and
relatively performance is high. |hence relatively performance is
low
Introduced in 1.2 version Introduced in 1.0 version and it is
a legacy class
|And it is non legacy class

ndsOFT
<br>

How to get synchronized version of


ArrayList Object?

• By default ArayList isObject is non-synchronized but we can get


synchronized version of ArayList by using Collection class
synchronizedlList () method.

public static List synchronizedList(List l)


<br>

How to get synchronized version of ArrayList Object?

public static List synchronizedList(List I)

Non-Synchronized
ArrayList 11=new ArrayList 0;

Synchronized
List I-Collections.synchronizedList (I1l);
<br>

How to get synchronized version of ArrayList Object?

* Similarly we can get Synchronized version of Set, Map Objects


by using the following methods of Collectionsclass.

Public static Set synchronizedSet (Set s);

Public static Set synchronizedMap (Map m);


<br>

LinkedList

* The underlying data structure is Double Linked List.


* Insertion order is preserved.

* Duplicates are allowed.


* Heterogeneous Objects are allowed.
* Null insertion is possible.
<br>

LinkedList
* LinkedList implements Serializable and Clonable interfaces
but not RandomAccess interface.

* LinkedList is the best choice if our frequent operation is


insertion or deletion in the middle.

*LinkedList is the worst choice if ourfrequent operation is


retrieval operation.
DURGASOFT
<br>

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

* LinkedList I1=new LinkedList);

Creates an empty Linked List Object

*LinkedList I1=new Linked List(Collecion c);


Creates an equivalent LinkedList Object for the given Collecion

DURGASOFT
<br>

LinkedList Dem0 program


import java.util. *;
public class LinkedListDemo {
public staticvoid main) {
LinkedList I1=new LinkedList ():
11.add (“durga");
l1.add (30);
|1.add (null);
I1.add (durga");
I1.set (0,"software");
Il.add (0,"venkey'");
I1.addFirst (“ccc);
System.out.println ():/|ccc,venkey,software,30,null]

DURGASOFT
<br>

Difference between ArrayList & LinkedList


Arraylist LinkedList

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.

*Heterogeneous objects are allowed.


*Vector class implemented Serializable, Cloneable and RandomAcoess Interfaces.
*Most of
themethods present in Vector are synchronized. Hence Vector object is
Thread-safe.
*Best choice if the frequent operation is retrieval.
DURGASOFT
<br>

Vector specificmethods

For adding objects:

add (Object o) [from Collection - List()]


add (int index, Object o) [from List]
addElement (Object o) [from Vector]

DURGASOFT
<br>

Vector specific methods

For removing Objects:


Remove (Object o) [from Collection ]
removeElement (Object o) [from Vector ]
remove (int index) [from List ]
RemoveElementAt (int index) [from Vector ]
clear () [from Collection ]
removeAlIElements () [from Vector ]

DURGASOFT
<br>

Vector specific methods


:
For Accessing Elements
Object get (int index) [from Collection ]

Object elementAt (int index) [from Vector ]

Object firstElement () [from Vector ]


Object lastElement () [from Vector ]

Other Methods:
int size();
int capacity ();
Enumeration elements ();
DURGASOFT
<br>

Constructors of vector class


1)Vector v= new Vector0:
-
Creates an empty vector object with default initial capacity 10,
Once vector reaches it's max capacitya new vector Object
will be Created with new capacity = 2 * current capacity.

2) Vector v= new Vector(int iniítialCapacity);


-
Creates an empty Vector Object with specified initial capacity

3) Vector v= new Vector(int initialCapacity, int incrermentalCapacity);

4) Vector v=new Vector(Collection c):


-Creates an
equivalent Vector Object for the
givangSOFT
<br>

Demo program for vector


import java.util.;
class VectorDemo {
public static void main(String arg[l) {

Vector v=new Vector (0;


System.out.printin (v.capacity ()); Ii10]
for (int i= 0;i<10 ;it+ ){
V.addElement (i);

System.out.println (v.capacity (0); W[10]


V.addElement("A");
System.out.println (v.capacity 0); II[20]
System.out.printin (v);
}
}

DURGASOFT
<br>

Stack

It is a child class of Vector.


*
It is specially designed class for Last In First Out order(LIFO)

DURGASOFT
<br>

Constructor of Stack

Stack s=new 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>

Demo program for Stack

import java.util.*;
class StackDemo{
public static void main (String arg[l) {

Stack s= new Stack ();


S.push ("A");
S.push ("B");
s.push ("C");
System.out.printin(s); /[A,B,C]
System.out.printin (s.search ("A")); M[31
System.out.println (s.search("")); /I[-1]

DURGASOFT
<br>

Three cursors of Java


retrieve Objects one by one from the Collection,
* If we want to
then we should go for Cursors.
*There are three types cursors are available in java.
of

* 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).

*We can create Enumeration Object by using elements()


method of Vector class.
(O);
Public Enumeration elements
:
Example
Enumeration e=V. elements ();

DURGASOFT
<br>

Method of Enumeration

*Enumeration defines the followingtwo methods


* public boolean hasMoreElements();
public Object nextElement();

DURGASOFT
<br>

Demo program for Enumeration

import java.util.*;
class EnumaretionDemo1{
Enumeration e v.elements ();
=
public static void main(String arg[]) {

Vector v= new Vector (0; while (e.has MoreElements(0){


for (int i =0;i<=10 ;it+){ Integer i= (Integer) e.nextElement ():;
V.addElement (i); if(i%2) ==0)
System.out.printin (i); //[0 2 4 6 8 10]
System.out.printin (v); /[0,1,2,3,4,5....10]
System.out.println (v); M[0,1,2,3,4,...10]

DURGASOFT
<br>

Enumeration
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 read access and we
can't perform remove operation.

Note: To overcome above limitations of Enumeration we should go for


Iterator.
DURGASOFT
<br>

Iterator
1. We can apply lterator concept for any Collection object
hence it is universal cursor.

2. By using Iterator we can perform both readand remove


operations.

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

* Iterator interface defines the following three methods.


i. public boolean hasNext ()
i. public Object next)
ii. public void remove)

DURGASO
<br>

Demo program for Iterator

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.

Note: Toovercome above limitations of Iterator we should go for Listlterator

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.

2. By using Listlterator we can perform replacement and


addition of new Objects in addition to read and renmove
operations.
DURGASOFT
<br>

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

forward direction Backward direction


1.public boolean hasNext () 4.public boolean hasPrevious()
2.public void next() 5.public void previous()
3.public int nextlndex () 6.public int previouslndex ()

other capability methods


7.public void remove()
8.public void set(Object new)
9.public void add(object new)
DURGASOFT
<br>

Demo program for ListIterator

import java.util.*; Listlterator Itr = 1. listlterator ();


class ListlteratorDemo { While (Itr. hasNext ()) {
Public static void main (String arg) { String s = (String) Itr.next ();
LinkedList | = new LinkedList (): if (s. equals ("venky")) {
l.add ("balakrishna"); Itr. remove ();
I.add ("chiru"); }else If (s. equals ("nag") {
L.add ("venky"); Itr.add ("chaitu'");
Ladd ("nag'"); } else if (s. equals ("chiru"){

System.out.println (); Itr. set ("charan");


I[balakrishna, venky, chiru, nag] }

System.out.println ();
II[balakrishna, charan,nag, chaitu]
}} DURGASOFT
<br>

Listlterator

Note: Listterator is the most powerfulcursor but its limitation is, it is


applicable only for List implemented dlass objects and it is not a

universal cursor.

DURGASOFT
<br>

Property Enumeration Iterator Listiterator


Applicable for Only legacy classes Any Collection classes Only List classes

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

Metho ds 2 methods 3 methods 9 methods


hasMoreElements() hasNext ()
nextElement() next()
remove()

Is it legacy "yes" (1.0v) "no" (1.2V) "no" (1.2V)

DURGASOFT
<br>

Implementation classes of cursors


import java.util.*;
class cursorDemo {

public static void main (String [] args) {

Vector v=new Vector ();


Enumeration e=v. element );
Iterator itr=v.iterator ();
Listlterator ltr= v.listlterator();
System.out.println (e.getClass (). getName (); Il java.uitl. Vector$1
System.out.printin (itr.getClass (). getName ()); /java.util. Vector$ltr
System.out.println (itr.getClass (). getName (); // java.util. Vector$Listltr

DURGASOFT
<br>

Set Interface :
Collection (1.2 version)

Set (1.2 version)

HashSet SortedSet o(I) (1.2 version)


(1.2 version)

NavigableSet (I)) (1.6 version)


LinkedHashSet
(1.4 version)
TreeSet (1.2 version)
DÜRGASOFT
<br>

Set
1. Set is the child interface of Collection.

2. If we want to represent a group of individual objects as a


single entity,where duplicates are not allowed and insertion
order is not preserved then we should go for Set.

3. Set interface doesn't contain any new methods. So we


have to use only Collection interface methods.
DURGASOFT
<br>

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

3) HashSet h = new HashSet(int initalCapacity,


foat loadFactor);
-
Createsan empty HashSet object with specified initial capacity
& specified Load Factor (or Fill Ratio)

4) HashSet h = new HashSe(Collection c);


-- For inter conversion between Collection
objrtIRGASOFT
<br>

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>

Demo program for HashSet


import java.util.*;
class HashSetDemo {
public static void main (String ] args) {

HashSet h=new HashSet ():


h.add("B");
h.add("C");
h.add("D");
h.add("Z");
h.add(null);
h.add(10);
System.out.printin (h.add("Z")); Ifalse
System.out.println (h); /[null, D, B, C, 10, Z]
}} 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)

|Insertion order is not preserved Insertion order is preserved

Introduced in 1.2 version Introduced in 1.4 version.

BURGASOFT
<br>

Demo program for LinkedHashSet


import java.util.";
class LinkedHashSetDemo {
public static void main (String ] args) {

LinkedHashSet h=new LinkedHashSet ();


h.add("B");
h.add("C");
h.add("D");
h.add("");
h.add(null);
h.add(10);
System.out.println M
(h.add("Z"); false
System.out.println (h); /[B, C, D, Z, null, 10]
}} DURGASOFT
<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)

1. It is the child interface of set.

2. If we want to represent a group of individual objects according to


some sorting order and duplicates are not allowed then we should
go for SortedSet.
<br>

SortedSet Specific methods


- retums first
Object first) element of
the SortedSet
Objsct last) -retums last element of the SortedSet

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.

2. TreeSet t-new TreeSet(Comparator c);


- Creates an empty TreeSet Object where elements will be inserted according to
CUstomized soring order.

3. TreeSet tnew TreeSet(SortedSet s);

4. TreeSet t-new TreeSet(Collecion c);


<br>

Example import java.util.


class TreeSetDemo{
public staic voidmain(Sting] args) {
new TreeSet():
TreeSet t=
tadd(A");
tadd(a);
t.add(B);
t.add(z");
tadd(L";
#ClassCasiExoepion
lLadd(new Intagar(10);
tadd(null; / NullPointerExcepionB,
System.out.prindn(% IA L,
Za
}
<br>

Null Acceptance

1. For empty TreeSet as the first element null inserion is possible.


But Afer inserting that nullif we are trying to insert any another element
we will get NullPointerException.

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.

* Hence in the above program we got ClassCastException **


<br>

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>

* If wedependingon default natural sorting order intermally JVM will


call Compare To() method will inserting objecis to the TreeSet. Hence
the objects should be Comparable.

TreeSet t = new TreeSet);


tadd('B')
tadd(Z"); Il compare To('B"); +ve
t.add(A"); Il "A'.compareTo(B"); ve
System.out.printin(t); MA, B, Z
<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.

2. Comparable ment for Default Natural Sorting order where as


Comparator ment for Customized Sorting order.
<br>

Comparator Interface

* We can use comparator to define our own sorting (Customized soring).


Comparator interface present in java.util package.
*lIt defines two methods. compare and equals.

1) public int compare(0bject obj1, Object obj2)


>
retums -ve ii obj1 has to come before obj2
returms +ve ii obj1 has to come afer obj2
retums Off obj1 obj2 are equal.
&

2) public boolean equals():


DURGASOFT
<br>

* When ever we are implementing Comparator interface, compulsory


we should provide implementation for compare) method.

* And implementing equals() method is optiornal, because it is already


available in every java cdass from Object class through inheritance.

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>

Integer Objects Into TreeSet, Desending order:


Treeset t-new Treeset(new MyComparator(); line1
tadd(10);
tadd(0): ve Compars(0,10);
tadd(15); compars(15,10);

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>

Various possible implementations of compare) method:

dass MyComparator implerments Comparator {

public int compars(Objec obj1, Object obj2){


Integer I1=(ntager)objl;
Integor 12-(Intogerjobj2;
Ilretum I11 CompareTo(2); 0,10,15,20] ascending order
lIreturm -1 CompareTo(2; 20,15,10,0]descanding order
Ilretum 12 CompareTo(1); 20,15,10,0] descending order
lretum -2 CompareTo(l1; 0,10,15,20] sscendirng order
II retum +1 10,0,15,20,20] Inserion order
Il retum -1 20,20,15,0,10] Reverse of lnserion order
Il return 0; [10]
(only first element willbe inserted and all he other elenments are considersd as duplicates)

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);
}
}

Output: [ShobhaRani, Roja, Ramulamma, RajaKum D


GRESOFT
<br>

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);
}

Output: A,AA,XX,ABC,ABCD] DURGASOFT


<br>

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.

2.But if we are defining our own sorting by comparator hen objects


nesd not be homogeneous and comparable. we can insert
heterogeneous non comparable objscis also.

DURGASOFT
<br>

1) For pradefined Comparable classes like Stingdefault natural soring order


already available. If we are not saisfied with that, we can define our owm
soring by Comparator object.
2) For Predefined non comparable dasses like StringBuffer, defaukt natural sorting
order is not already available. We can define required sorting by implementing
Comparator interface.
3) For our own classes like Employee, Student, Customer), the person who is
writing our own dass, he is responsible to define default natural sorting order
by implemernting Comparable interface.
The person who is using our class, if he is not satisfied with default natural
sorting order, then he can define his own sorting by using Comparator.

DURGASOFT
<br>

Pre - deined claues


pre - defiJ
Comporolle
Claues
clane
(i st-le) The
pe rAn

The

Come valle,Cz) ComaratCI)


Compeyatr Comyrey oti
Defoult Nohu
ode.

DURGASOFT
<br>

Demoprogram for Customized sorting for Employee class : (Page 1 of 3)

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>

Demo program for Customized sorting for Employee class : (Page 2 of 3)

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>

Demo program for Customized sorting for Employee class : (Page 3 of 3)

dlass MyComparator implements Comparator {


public int compare(Object obj1, Object obj2) {
Employee eL = (mployee)obj1;
Employee e2 = (Bmployee)objz;
String s1=e1.name;
String s2=e2.name;
return si.comparelos2);
}
}
<br>

Comparison table of Comparable and Comparater

Comparable Comparator
1. Itis meant for default natural sorting order. 1. Itis meant for customized sorting order.

2. Present in java.lang package. 2. Present in java.util package


3. This interface defines only one method compare To () 3. This interface defines two methods compare) and equals).

4. All wrapper classes and String class implement comparable 4. The only implemented classes of Comparator are Collator and
interface. RuleBasedCollator.

DURGASOFT
<br>

Comparison table of Set(l) implemented classes

Property HashSet LinkedHashSet TreeSet


1. Underlying Data Structure Hashtable Hashtable + LinkedList Balanced Tree

2. Insertion Order Not Preserved Preserved Not Applicable

3. Sorting order Not Applicable Not Applicable Applicable

4. Heterogeneous objects Allowed Allowed Not Allowed

5. Duplicate Objects Not Allowed Not Allowed Not Allowed

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

You might also like