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

Collections Framework

The document provides an overview of the Java Collections Framework, detailing the Iterator interface, the differences between arrays and collections, and various collection interfaces such as List, Set, and Map. It explains the purpose of collections, their advantages over arrays, and key methods associated with different collection types. Additionally, it highlights the differences between ArrayList and Vector, including their synchronization and performance characteristics.

Uploaded by

Jagdish Varun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Collections Framework

The document provides an overview of the Java Collections Framework, detailing the Iterator interface, the differences between arrays and collections, and various collection interfaces such as List, Set, and Map. It explains the purpose of collections, their advantages over arrays, and key methods associated with different collection types. Additionally, it highlights the differences between ArrayList and Vector, including their synchronization and performance characteristics.

Uploaded by

Jagdish Varun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Collections

Iterator interface

Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public boolean It returns true if the iterator has more


hasNext() elements otherwise it returns false.

2 public Object next() It returns the element and moves the


cursor pointer to the next element.

3 public void remove() It removes the last elements returned by the iterator.
It is less used.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()
Q what is need of collection or what is the purpose to use of collection?
Ans:- yadi hum 1 value ko store karna cahate hai to hume ek variable declare karna hoga ase hi
yadi 2 value store karna hai to hume 2 variable declare karna padega Ase hi yadi hume 200000
value store karna hai hai hume utne hi variable declare karna hoga jisse ye kam bahot complex ho
jayege . To eske liye hum array ka use kar sakte hai.

Like :- int x[ ] = new int[200000];

Limitation of array:- Array is fixed in size once we created array there is no chance of increase
and decries the size based on our requirement.

• We have to always know the size some time which is not possible.EX:- Movie booking.
• Array can hold only homogeneous type of data type elements but we can solve this
problem by Object type array.
Ex:- Object a=new Object[100];
Student[0] =new Student();
Teacher[1]=new Teacher();
• Array ka concept kuch standard Data Structure ke based pr hi ho sakta . har Collection
class implement ho sakti hai.

Why we use Collections:-

• Collections are growable in nature we can incrise and dicrise it .


• It can hold homogeneous and heterogeneous type of Objects and data type.

-----------------------------------------------------------------------------------------------------------------

L-2
Difference between Array and Collections.
Array Collections
• Fixed size. Growable in nature.
• Memory ke respect me hum Array ka use nhi karte. eska karte hai.
• Performance ke regarding eska use karte hai. eska nhi karte ye slow hai.
• Ye homogeneous data hold ker sakte hai . ye dono ko ker sakta hai.
• Data Structure ki readymade classes ko support nhi ye karta hai .
Kerta hai.
• Esme hum primitive data type and object ko esme only Objects ko hold
Hold ker sakte hai. ker sakte hai.

Array and any Collection concept pr difference puche to yahi batana hai .

-----------------------------------------------------------------------------------------------------------------

L-3

Collection and Collections


(i) Collection:-yadi hum group of individual objects ko single antity me
represent karna cahate hai to hume collecton use karna cahiye. EX:- group
of student.
Collection FrameWork:-ye bahot sare interface and class ka collection hota hai jo ki
objects ke grop ko single entity ke tarha use karte hai.

• Java and C++ dono me Collection Framework hota hai but termlogy different hai.
Java C++
*Collection Container
*Collection FrameWork STL(Standard Template Library).

Library mtlab group of interfaces and classes.


-----------------------------------------------------------------------------------------------------------------

L-4
9 key interfaces of collection Framework
1:- Collection:- yadi hum group of individual object ko 1 single entity ki tarha represent
karna cahate hai to hume Collection ka use karna cahiye.
• Collection interface ke pass bahot sari most commonly used method hai jo ki collection ke
object ke sath use ho sakti hai.
• Gunreally collection interface Collection Framework ka root interface mana jata hai.

Note:- ase koi concrete class nhi hai jo ki collection interface ko directly implement ker sake.

-----------------------------------------------------------------------------------------------------------------

L-5
Diffreance between Collection and Collctions

Collection Collctions
• Collection is a interface . Collections is a class.
• Yadi hum group of individual objects Collections utility class hai jo ki
Ko as a single entity represent karna java.util package me hai. jo ki
cahate hai to eska collection object ke liye bahot sari
use karege. method define karti hai(shorting,serch).

-----------------------------------------------------------------------------------------------------------------

L-6
(ii) List interface

• List child interface hai collection interface ka.


• Yadi hum group of individual object ko as a single entity me represent karna cahata hai.
jaha dublication allow ho and insertion order preserved ho.
• Collection and List interface then ArrayList , LinkedList classes came in version 1.2 and but
Vector and Stack came in 1.0 version. Esliye Vector and Stack class jo legacy class bhi kahte
hai means old class.

-----------------------------------------------------------------------------------------------------------------

L-7
(iii) Set

• Set child interface hai collection interface ka.


• Yadi hum group of individual object ko as a single entity represent karna cahata hai. jaha
dublication allow nhi ho and insertion order preserved nhi ho.
• Collection, Set interface and HashSet class came in version 1.2 but LinkedHashSet class
came in version 1.4.
-----------------------------------------------------------------------------------------------------------------
L-8
Difference between List and Set

List Set

• Duplicates allowed nhi hai. Duplicates allowed hai.


• Insertion order preserved hota hai . Insertion order preserved nhi hota hai.
-----------------------------------------------------------------------------------------------------------------

L-9
(iv)SortedSet
• Sortedset child interface hai Set interface ka.
• Yadi hum group of individual object ko as a single entity represent karna cahata hai. jaha
dublication allow nhi ho and insertion order preserved nhi ho. But sabhi objects ko some
sorted order kai according insert hona cahiye to hum SortedSet ka use karte hai.
• Collection, Set interface and ShortedSet version 1.2 me aye the.

(v) NavigableSet
• NevigableSet SortedSet ka child interface hai .ye navigation purpose ke liye bahot sari
method deta hai.
• Collection, Set interface and ShortedSet version 1.2 me aye the. And NavgationSet came
in version 1.6 and TreeSet came in 1.2 version.
-----------------------------------------------------------------------------------------------------------------

L-10
(vi) Queue
• Queue child interface hai Collection ka.
• Yadi hum group of individual object ko prior to processing me represent karna cahate
hai.so hume Queue ka use karna cahiye.
• EX:- mail send karne se pahle sabhi mail Id ko hume kahi store karna hota hai and jis order
me hum mail send karte hai usse order me vo send hote hai(First in First Out) es
requirement ke liye Queue ka option best hai.
• Queue(1.5) child interface hai Collection(1.2) interface ka. PriorityQueue(1.5) and
BlockingQueue(1.5) child interface hai Queue ka. LinkedBlockingQueue(1.5) and
PriorityBlockingQueue(1.5) is child classes of BlockingQueue.
• Ye sabhi interfaces(Collection, List, Set, SortedSet, NavigableSet ,
Queue) jab hume group of individual object ko represent karna hota hai tab use karte hai.
• Yadi hum group of object ko as a key value pairs represent karna cahate hai to hume Map
interface ka use karna hoga.
-----------------------------------------------------------------------------------------------------------------

L-11
(Vii)Map
• Map Collection ka child interface nhi hai. 3 esliye hi hum ye nhi kah sakte ki collection is
root interface of collection FrameWork.
• Yadi hum group of individually objects ko key pair ke roop me present karna cahate hai to
hume Map ka use karna cahiye.
• Ex:-
• Roll No. Name
101 Ram
102 Manish
103 Arun
• Both key and value are objects , duplicated key are not allow value can be
HashMap(1.2), WeakHashMap(1.2) ,IdentityHasMap(1.4) ,Hastable(1.0) is child interface
of Map(1.2) interface. LinkedHashMap(1.4) is class of HashMap.
-----------------------------------------------------------------------------------------------------------------
L-12
(viii)SortedMap
• It is child interface of Map
• Yadi hum group of key value paires ko sorting order of key ke roop me represent karna
cahate hai. to SortedMap ka use karte hai.
• ShortedMap(1.2) is child interface of Map(1.2).

(ix)NavigableMap
• NavigableMap(1.6) is child interface of SortedMap(1.2).
• it defines several utility method for navigation purpose.
• TreeMap is class of NavigableMap interface.
-----------------------------------------------------------------------------------------------------------------
L-13
Overview of Collection framework
Q what is the difference between Comparable interface and Comparator interface

Ans:-Comparable meant for default natural sorting order and comparator meant for coustumaiger
sorting order.

Yadi hum object ko one by one get karna cahate hai collection se to cursers concept available hai.

There are 3 type of cursers available in java:-

(i):-Enumeration interface.

(ii):-Iterator interface.

(iii):-ListIterator interface.

There are 2 utility classes are available in collection FrameWork.

(i):-Collections is a utility class to defines several utility methods for collection Objects.

(ii):-Arrays is a utility class to defines several utility methods for Arrays Objects.

• Legacy class of Map:- Hashtable , Dictionary, Properties.


-----------------------------------------------------------------------------------------------------------------

L-14
Collection interface details

Collection framework defines most common methods. Which are applicable for any collection
object.

i. boolean add(object o):- for add one object.


ii. boolean addAll(Collection c):- for add group of objects.
iii. boolean remove(object o):- for remove particular object.
iv. boolean removeAll(collection c):- for remove group of objects.
v. void clear():- for remove all objects.
vi. boolean retainAll(Collection c):- Except only some Selected object are present then all
object remove.
vii. boolean isEmpty():- for check collection is empty or not.
viii. int size():- what is the size of collection.
ix. boolean contains(object o):- is collection that particular object is contains or not .
x. boolean containsAll(collection o):- for check group of object is available or not.
xi. Object[] toArray():- for convert collection to array .return type of this method is Object
array.
xii. Itrator iterator():- for get one by one object.it return iterator objects.
Note:- collection interface does not contain any method to retrieve objects. There is
no concrete class which implements collection class directly.
-----------------------------------------------------------------------------------------------------------------
L-15
List interface details
• Ye collection ka child interface hai.
• Ager hum group of individual object ko single entity me represent karna cahate hai. jaha
duplication allow ho and insertion order preserved ho.to List ka use karege.
• Hum duplication ko index value se diffrentiat ker sakte hai.
• Hum insertion order ko indexing se preserved ker sakte hai.esliye index bahot important
role play karta hai.
• Humne jo collection ki jo method discuss ki hai vo sabhi to use kar hi sakte hai sath hi List
ke pass kuch or methods bhi hai.
i. void add(int index,Object o):- for add any object at particular index number.
ii. boolean addAll(int index, Collection c) :- for add group of objects.
iii. object remove(int index):- for remove object from particular index.
iv. int indexOf(“object name”):- for get index number of particular object.
v. int lastIndexOf(“object name”):- for get last time that object is available.
vi. object get(index number):- for get object of that index.ager present nhi hoga
to null dega.
vii. ListIterator listIterator():- for iterat objects from list.
viii. object set(int index, new object ):- for replace value at the particular index
where other object is present already.
-----------------------------------------------------------------------------------------------------------------

L-16
ArrayList details (Collection Framework)
• Array list me underlined data structure Resizable array and Growable Array hai.
• Duplication allow hai.
• Insertion order preserved hota hai.
• pure collection framework me serf 2 place ko chod ker har jagha heterogeneous object
allow hai.1.TreeSet and 2.TreeMap . kyo ki enme object some sorting order me store hote
hai.
• Null insertion possible hai.
ArrayList Constuctors:-
• There are 3 important constructor are available in ArrayLIst.
• (1):-ArrayList a=new ArrayList();
• Empty ArrayList ki initial capacity 10 hoti hai. jab ek bar ArrayList uski last capacity pr
pahoch jati hai to new list new capacity ke sath create ho jati hai and first list ke sare
objects new vali list me aa jate hai or old vali empty ho jati hai jise garbage collector
destroy ker deta hai.
• New ArrayList create formula :- (CurrentCapacity*3/2)+1
• (2):- ArrayList a=new ArrayList(int initial capicity). Ye list tab create karte hai jab hume pta
ho ki etne object to first me ana hi hai. to yadi ase crete karege to performance badh
jayege .
• (3):- ArrayList a=new ArrayList(Collection c). ye tab use karte hai jab hume other List ke
equivalent ArrayList crate karna ho tab.es type ke Constructor collection ke object ke
beach inter conversion ke liye use kiye jate hai. like LinkedList to ArrayList, Vector to
ArrayList or TreeSet to ArrayList .And so on.
Ex:-
import java.u til.*;
public class ArrayList2 {
public static void main(String arr[]) {
ArrayList l=new ArrayList();
l.add(1);
l.add("Ram");
l.add("BCA");
l.add("Indore");
System.out.println(l); //[1, Ram, BCA, Indore]
l.add("MP");
System.out.println(l); // [1, Ram, BCA, Indore, MP]
l.remove(1);
System.out.println(l); // [1, BCA, Indore, MP]
l.set(3,"2");
System.out.println(l); // [1, BCA, Indore, 2]

}
}
• Aksar hum Collection interface ka use object ko hold karne and one place se other place pr
transfer karne ke liye karte hai. es requirement ko support karne ke liye har collection
already Serializable and Cloneable interfaces implements karta hai.

This points are only related ArrayList and Vecter:-


• ArrayList and vecter classes implements RandomAccess interface. So that we can access
any random element with the same Speed.
• If our choice is retrival opration so we can use ArrayList is the best choice
RandomAccess interface:-
• RandomAccess is available in java.util package.
• It does not contains any methods. It is marker interface.
Q when we should use ArrayList and we should not use.
Ans:-ArrayList is the best choice if our frequent operation is retrieval operation. (Because
ArrayList implements RandomAccess interface).
• Array list is the worst choice our frequent operation is insertionor deletion in the
middle.(Because several shift operations are required which takes time. )
-----------------------------------------------------------------------------------------------------------------

L-17
Differences between ArrayList and Vector

ArrayList Vector
• Every method present in ArrayList is Every method present in
non Synchronized. Vector is synchronized.
• At a time multiple thread are allow to At a time one thread is allow
Operate on ArrayList object That’s why it to operate on vector that’s
is not thread safe. why it is thread safe.
• Threads are not required to wait to Threads are required to wait
Operate on ArrayList , that’s why relatively to Operate on Vector Object.
Performance is high. that’s why relatively
Performance Is low.
• Introduce in version 1.2 . Introduce in version 1.0 .
• It is non legacy. It is legacy.
-----------------------------------------------------------------------------------------------------------------

L-18
How to get Synchronized version of ArrayList

By default ArrayList is non-synchronized.But we can get synchronized version of ArrayList by using


Collections class synchronizedList() method.

Public static List synchronizedList(List l)

Non-synchronized :- ArrayList a=new ArrayList();

Synchronized:- List l=Collections. synchronizedListe(a);

Similarly we can get synchronized version of Set, Map Objects by using the following methods of
Collections class.

public static Set synchronizedSet(Set s);

public static Map synchronizedMap(Map s);

-----------------------------------------------------------------------------------------------------------------

L-19
LinkedList details
• Insertion and deletion ke liye Linked list ka use karte hai. kyo ki esme nodes bante hai jisko
kahi bhi add and delete ker sakte hai.
• Underliying data Structure is double linked list .
• Insertion order is preserved.
• Heterogeneous Objects are allowed.
• Null insertion is allowed.
• LinkedList implements Serializable and Cloneable interface but not RendomAccess
interface.
• LinekedList is the best choice if our frequent operation is insertion or deletion in the
middle.
• LinekedList is the wrost choice if our frequent operation is retrieval operation.
• Usually we can use LinkedList to implements Stack and Queue to provide support for this
requirement LikedList class defines following specific methods:-
void addFirst(object);
void addLast(object);
Object removeFirst();
Object removeLast();
Object getFirst();
Object getLast();

LikedLIst constructor
There are 2 type of constructor in Linkedlist:-

1. Create an empty LikedList Object


Ex:- LinkedList l=new LinkedList();
2. Create an equivalent LinkedList object for given Collection.
Ex:-LinkedList ll=new LisnkedList(Collection c)
-----------------------------------------------------------------------------------------------------------------

L-20
Differences between ArrayList and LinkedList

ArrayList LinkedList
• ArrayList is the best choice if our LinkedList is the best choice if our
Frequent operation is retrieval. Frequent operation is insertion or
Deletion.
• ArrayList implements RandomAccess LinkedList doesn’t implements
Interface. RandomAccess interface.
• Underling data Structure for Underling data Structure for
ArrayList is Resizable and Growable LinkedList is Double LinkedList.
Array.
• ArrayList is the wrost choice if our LinkedList is the wrost choice if
frequent operation is Insertion or our frequent operation is
Deletion. Retrieval.
-----------------------------------------------------------------------------------------------------------------

L-21
Vector class details

• Underling data Structure for Vector is Resizable and Growable Array.


• Duplicate objects are allowed.
• Insertion order is preserved.
• Null insertion is possible.
• Heterogeneous objects are allowed.
• Vector class implements Serializable, Cloneable and RendomAccess interface.
• Most of methods present in Vector are Synchronized. That’s why Vector is thread-safe.
• Best Choice if frequent operation is retrieval.
• Only one difference between Vector and ArrayList is Vector is
thread-safe but ArrayList is not Thread-safe.

For Adding Objects methods:-

add (object o) :- [Come From Collection List]

add (int index object o) :- [Come From List]

addElement (object o) :- [Come From Vector]

For Removeing Objects methods:-


remove(Object o) [From Collection]

removeElement(Object o) [From Vector]

remove(int index) [From List]

removeElementAt(int index) [From Vector]

clear() [From Collection]

removeAllElements() [From Collection]

For Retrieve Elements methods:-


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

Constructor of Vector:-
1. Creates an empty Vector Object with default initial capacity 10, Once Vector reaches at it’s
max capacity a new Vector object will be created with new Capacity =2*Current Capacity.
Ex:-Vector v=new Vector();
2. Creates an empty Vector Object with specified capacity.

Ex:-Vector v=new Vector(int initialCapacity);

3. Ex:-Vector v=new Vector(int initialCapacity,incrementalCapacity);


4. Creates an equivalent Vector Object for the given Collection
Ex:-Vector v=new Vector(Collection c);
-----------------------------------------------------------------------------------------------------------------

L-22
Stack class details
• It is child class of Vector class.
• It is spacialy designed class for LIFO(Last In First Out).

Constructor of Stack:-
Stack s=new Stack();

Stack Methods:-
1. Object push(Object obj):-For inserting object in stack.
2. Object pop():-To remove and returns top of the Stack.
3. Object pick():-to returns top of the object without remove of Object.
4. Int serch(Object obj) :- if the spacified object is present. So it returns number from top of
the Stack.
If the object is not available it returns -1.
5. Object pop:- for inserting Object to the Stack.
-----------------------------------------------------------------------------------------------------------------

L-23
Three Cursors of Java - Enumeration

Three Cursors of Java:-


• If we want to retrieve Object one by one from the collection then we should go for
cursors.
• There are three types of cursors are available in java:-
1. Enumeration.
2. Iterator.
3. ListIterator.

Enumeration:-
• Introduced in version 1.0 (for lagacy).
• We can use Enumeration for get object one by one from the old collection Object (Legacy
Collections).
• We can create Enumeration Object by using elements() method of Vector class. Public
Enumeration elements();
• Ex:- Enumeration e=v.elements();

Method of Enumeration:- it contains only 2 methods.


1. public boolean hasMoreElements();
2. public Object nextElement();
Limitation of Enumeration:-
• Enumeration Concept is applicable only for legacy classes. that’s why it is universal cursor.
• By using Enumeration we can get only Read access and we can’t perform remove
operation.

Note:- for overcome to this limitation of Enumeration we should go for Iterator.

-----------------------------------------------------------------------------------------------------------------

L-24
Three Cursors of Java – Iterator
• We can apply Iterator concept for any collection Object that’s why it is universal courser.
• By using Iterator we can perform both read and remove operations.
• We can create Iterator object by using iterator() method of collection interface.
public Iterator iterator();
Ex:- Iterator itr=C.iterator();
Where C Is any collection object.

Methods of Iterator interface:-


• public boolean hashNext();
• public Object next();
• public void remove();

Limitations of Iterator:-
• By using Enumeration and Iterator we can move only in forward direction and we cannot
move it in backward direction. That’s why this are single direction coursers.
• By using Enumeration and Iterator we perform only read and remove operations. We
cannot perform replacement of new Objects.
• To overcome from this problem we should go with ListIterator.
-----------------------------------------------------------------------------------------------------------------

L-25
Three Cusors of Java ListIterator
• By using ListIterator we can move either to forward direction and backward direction.
That’s why this are bidirectional coursers.
• By using ListIterator we can perform replacement of new Object and read and remove
operation.
• We can create LIstIterator object by using listIterator() method of List interface.
public ListIterator listIterator();
Example:- ListIterator itr=l. listIterator();
Where l is List Object.

Methods in ListIterator:-
• ListIterator is the child interface of Iterator. That’s why all method of Iterator are by
default available in ListIterator.
• ListIterator interface defines the following 9 methods.
• Forward Direction :-
i. public boolean hashNext();
ii. public void next();
iii. public int nextIndex();
• BackWard Direction :-
i. public boolean hashPrevious ();
ii. public void previous ();
iii. public int previousIndex();
• Other Capability methods:-
i. public void remove();
ii. public void add(Object new);
iii. public void set(Object new);

Note:- ListIterator is the most powerful courser but it’s limitation is , it is application only for List
implemented classes Object and it is not universal courser.

-----------------------------------------------------------------------------------------------------------------

L-26
Comparison of the three Cursors of Java
Property Enumeration Iterator ListIterator
Applicable for. Only legacy classes. All Collection classes. only List classes.

Movement. Only Forward Direction Only Forward Direction. Both directions

(Single Direction). (Single Direction). (bidirection).

Accessibility. Only read access. Only read and remove read, remove, replace

Access. and addition of new

Objects.

How to get it. By using elements() method By using iterator()method By using listIterator()

Of vector class. Of collection interface. Method of List interface.

Methods. 2 methods 3 methods hashNext() 9 methods.

hashMoreElement(); next();

nextElement(); remove();

Is it legacy. “Yes” version 1.0 “no” version 1.2 “no” version 1.2

-----------------------------------------------------------------------------------------------------------------
L-28
HashSet
Set:-
Set[1.2] is child interface of Collection[1.2], HashSet[1.2] and LinkedHashSet[1.4] are class of
Set interface. SortedSet[1.2] and NavigableSet[1.6] are child interface of Set
interface.TreeSet[1.2] is class of NavigableSet.

• Set is child interface of Collection.


• If we want to represent group of individual Objects as the single entity. Where duplicates
are not allowed and insertion order not preserved. So we should use Set.
• Set interface does not contain any new methods. So we have to use only Collection
interface methods.

HashSet:- The underling data Structure is Hashtable.


• Duplicates are not allowed. If are trying to insert duplicate objects. We will not get any
compile time and runtime error. add() method simply returns false.
• Insertion is not preserved and all Objects will be inserted on the bases of Hash-Code of
Objects.
• Heterogeneous objects are allowed.
• “Null” insertion is possible.
• Implements Serializable and Colnable interface but not RandomAccess interface.
• Hashset is best choice if our frequent operation is Search operation.

Constructor of HashSet:-

• Creates an empty HashSet Object with default initial Capacity 16 and default fill Retio 0.75

Ex:- HashSet h=new HashSet();

• Creates an empty HashSet Object with Specified initial Capacity and default fill Retio 0.75.
Ex:- HashSet h=new HashSet(int initialCapacity);
• Creates an empty HashSet Object with Specified initial Capacity and Specified loadFactor(
or fill Retio)
Ex:- HashSet h=new HashSet(int initialCapacity , float loadFactor);
• For inter conversion between 2 Collection Objects.
Ex:- HashSet h=new HashSet(Collection c);

loadFactor( or fill Retio) :- After Loading the how much factor, a new HashSet Object will be
created, that factor is called As Load Factor and Fill Retio.

-----------------------------------------------------------------------------------------------------------------

L-29
LinkedHashSet
• It is child class of HashSet.
• Introduced in version 1.4
• It is same as HashSet apart from following difference.

HashSet LinkedHashSet

• The underling data Structure The underling data Structure


Is Hashtable. IsHashtable + 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.

Note:- LinkedHashSet is the best choice to develop cache based application, Where
duplicates are not allowed and insertion order must be preserved.

-----------------------------------------------------------------------------------------------------------------

L-30
SortedSet Details

• It is child interface of Set.


• If we want to represent group of individual objects according to some sorting order.
Where duplicates are not allowed.So we should use SortedSet.

SortedSet Spacific methods:-


• Object first():- return first element of SortedSet.
• Object last():- return last element of SortedSet.
• SortedSet headSet(Object obj):- return the sortedSet whose elements are < obj
• SortedSet tallSet(Object obj):- return the sortedSet whose elements are >= obj
• SortedSet subSet(Object obj1 , Object obj2):- return the sortedSet whose elements are >=
obj1 and <obj2 .
• Comparator comparator():- returns Comparator objects that describes underling Sorting
technique.If we are using default natural sorting order so we will get null.

Example:- {100,101,103,104,107,110,115}
• first():- 100;
• last():- 115;
• headSet(104):- [100,101,103];
• tallSet(104):- [104,107,110,115];
• subSet(103,110):- [103,104,107];
• comparator():- null ;

Note:-
• default natural sorting order for number is ascending order. And for String alphabetical
order.
• We can apply above methods only on SortedSet implemented class Object. That is on the
TreeSet Object.

-----------------------------------------------------------------------------------------------------------------

L-31
TreeSet Details
• The underling data structure for TreeSet is Balanced Tree.
• Duplicate objects are not allowed.
• Insertion order not preserved, But all objects will be inserted in some sorting order.
• Heterogeneous objects are not allowed .If we are trying to insert. If we are Trying to insert
Heterogeneous objects. So we will get Run time Exception ClassCastException.
• Null insertion is allowed, but only once.

TreeSet Constructor:-
• Creates an empty TreeSet object. Where elements will be inserted according to default
natural sorting order.
Ex:- TreeSet t=new TreeSet();
• Creates an empty TreeSet object. Where elements will be inserted according to
customized sorting order.
Ex:- TreeSet t=new TreeSet(comparator c);
• Ex:- TreeSet t=new TreeSet(SortedSet s);
• Ex:- TreeSet t=new TreeSet(Collection c);

Null Acceptance:-
• For empty TreeSet as the first element null insertion is possible. But after inserting that
null. If we are trying to insert any other element we will get NullPointerException.
• For non-empty TreeSet If we are trying to insert null then we will get
NullPointerException.
-----------------------------------------------------------------------------------------------------------------
L-32
• If we are depending on default natural sorting order then objects should be
Homogeneous and Comparable. Otherwise we will get runtime exception.
ClassCastException.
• An object is said to be Comparable if and only if the corresponding class implements
java.lang.comparable interface.
• String class and all wrapper classes already implements Comparable interface. But
StringBuffer doesn’t implements Comparable interface.

-----------------------------------------------------------------------------------------------------------------
L-33
Comparable interface
• This interface present in java.lang package it contains only one method compareTo()
public void compareTo(Object obj);
Example:-
obj1.compareTo(obj2);
• Returns –ve if obj1 has to come before obj2.
• Returns +ve if obj1 has to come after obj2.
• Returns 0 if obj1 and obj2 are equal.

(“A”.compareTo(“Z”)); //-ve

(“Z”.compareTo(“B”)); //+ve

(“A”.compareTo(“A”)); //0

(“A”.compareTo(“null”)); //NullPointerException

• If we depending on default natural sorting order internally JVM will call compareTo()
method will inserting Object to the TreeSet. Hence the Object should be Comparable.
• Ex:-
TreeSet t= new TreeSet();
t.add(“B”);
t.add(“Z”); //”Z”.compareTo(“B”) +ve
t.add(“A”); //”A”.compareTo(“B”); -ve
System.out.println(t);//[A,B,Z]

Note:- if we are not satisfied with default natural sorting order or if default natural sorting is not
already available then we can define our own customized sorting order by using Comprator.

• Comparable meant for default natural sorting order. Where as Comparator meant for
Customized sorting order.

-----------------------------------------------------------------------------------------------------------------

L-34
Comparator interface
• We can use Comparator for define our own sorting (Customized sorting).
• Comparator interface present in java.util package .
• It defines 2 methods compare() and equals().
Ex:- public int compare(Object obj1 ,Object obj2);
• Returns –ve if obj1 has to come before obj2.
• Returns +ve if obj1 has to come after obj2.
• Returns 0 if obj1 and obj2 are equal.
Ex:- public boolean equals();

• Whenever we are implementing Comparator interface. Compulsory we should provide


implementation of compare() method.
• Implementing equals() method is optional, because It is already available in every java
class from Object class through inheritance.

-----------------------------------------------------------------------------------------------------------------

L-38
Note:- if we are depending on default natural sorting order then Objects should be
Homogeneous or Comparable otherwise we will get runtime
exception.ClassCastException.
• But we are defining our own sorting by Comparator then Objects need not to be
Homogeneous or Comparable. We can insert Heterogeneous and non Comparator
Objects also.

-----------------------------------------------------------------------------------------------------------------

L-39
Comparable vs Comparator
• For predefine Comparable class like String default natural sorting order is already
available. If we are not satisfied with that we can define our own sorting order by
Comparator Object.
• For predefine non Comparable class like StringBuffer , default natural sorting order is
not already available. We can define required sorting order by implementing
Comparator object.
• For our own class like (Student, Employee) the person who is writing our own class he
is responsible to define default natural sorting order by implementing 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.

-----------------------------------------------------------------------------------------------------------------

L-41
Differences between Comparable and Comparator

Comparable Comparator

• It is meant for default natural It is meant for default natural customized


sorting order. sorting order.
• Present in java.lang package Present in java.util package
• This interface defines only one This interface defines only two methods
Method compareTo(). compare() and equal().
• All String and wrapper classes are the only implementes class of Comparator
Implements Comparable interface. are Collator and RuleBasedCollator.

-----------------------------------------------------------------------------------------------------------------
L-42
Comparison table of Set implemented classes
Property HashSet LinkedHashSet TreeSet
Underling Data Structure. Hashtable. Hashtable + LinkedList. Balanced Tree.

Insertion order. Not preserved. preserved. Not Applicable.

Sorting order. Not Applicable. Not Applicable. Applicable.

Heterogeneous Object. Allowed. Allowed. Not Allowed.

Duplicate Objects. Not Allowed. Not Allowed. Not Allowed.

Null Acceptance. Allowed(only Allowed(only For Empty TreeSet as first

once). once). Element Null is allowed and

in all other cases we will get

NullpointerException.

************************End************************

You might also like