Collections Framework
Collections Framework
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
3 public void remove() It removes the last elements returned by the iterator.
It is less used.
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.
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.
-----------------------------------------------------------------------------------------------------------------
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
• Java and C++ dono me Collection Framework hota hai but termlogy different hai.
Java C++
*Collection Container
*Collection FrameWork STL(Standard Template Library).
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
-----------------------------------------------------------------------------------------------------------------
L-7
(iii) Set
List Set
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.
(i):-Enumeration interface.
(ii):-Iterator interface.
(iii):-ListIterator interface.
(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.
L-14
Collection interface details
Collection framework defines most common methods. Which are applicable for any collection
object.
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.
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
Similarly we can get synchronized version of Set, Map Objects by using the following methods of
Collections class.
-----------------------------------------------------------------------------------------------------------------
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:-
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
Other methods:-
int size();
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.
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
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();
-----------------------------------------------------------------------------------------------------------------
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.
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.
Accessibility. Only read access. Only read and remove read, remove, replace
Objects.
How to get it. By using elements() method By using iterator()method By using listIterator()
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.
Constructor of HashSet:-
• Creates an empty HashSet Object with default initial Capacity 16 and default fill Retio 0.75
• 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
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
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();
-----------------------------------------------------------------------------------------------------------------
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
-----------------------------------------------------------------------------------------------------------------
L-42
Comparison table of Set implemented classes
Property HashSet LinkedHashSet TreeSet
Underling Data Structure. Hashtable. Hashtable + LinkedList. Balanced Tree.
NullpointerException.
************************End************************