0% found this document useful (0 votes)
25 views86 pages

14 Collections Frame Work

The document provides a comprehensive overview of Java's Collections Framework, detailing various collection types such as Lists, Sets, and Maps, along with their advantages over traditional arrays. It highlights the limitations of arrays, including fixed size and homogeneous data types, and emphasizes the flexibility and utility of collections. Key interfaces and methods within the Collections Framework are also discussed, illustrating how they facilitate the management of groups of objects in Java programming.

Uploaded by

yashharode9890
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)
25 views86 pages

14 Collections Frame Work

The document provides a comprehensive overview of Java's Collections Framework, detailing various collection types such as Lists, Sets, and Maps, along with their advantages over traditional arrays. It highlights the limitations of arrays, including fixed size and homogeneous data types, and emphasizes the flexibility and utility of collections. Key interfaces and methods within the Collections Framework are also discussed, illustrating how they facilitate the management of groups of objects in Java programming.

Uploaded by

yashharode9890
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/ 86

JAVA Means DURGA SIR

1DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Collections Frame Work


Collections
List
ArrayList
LinkedList
Vector
Stack Set
HashSet
LinkedHashSet SortedSet
NavigableSet
TreeSet
Queue
PriorityQueue
BlockingQueue
PriorityBlockingQueue
LinkedBlockingQueue

Map
HashMap
LinkedHashMap WeakHashMap
IdentityHashMap
Hashtable
Properties SortedMap
NavigableMap
TreeMap
❖ Iterator (I) Sortin
Cursors Utility Classes ❖ Comparable (I)
❖ Enumerations (I) Collection s

An Array is an Indexed Collection of Fixed Number of Homogeneous Data Elements. The Main
Advantage of Arrays is we can Represent Multiple Values by using Single Variable so that
Readability of the Code will be Improved.

2DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Limitations Of Object Type Arrays:

1) Arrays are Fixed in Size that is Once we created an Array there is No Chance of Increasing
OR Decreasing Size based on Our Requirement. Hence to Use Arrays Concept Compulsory
we should Know the Size in Advance which May Not be Possible Always.
2) Arrays can Hold Only Homogeneous Data Type Elements.
Student[10000]; s[0] =
Eg: new Student();√
Student[] s = new
CE: incompatible types
s[1]=new found: Costomer
Customer(); required: Student

We can Resolve this Problem by using Object Type Arrays.


= new Student(); √
Eg: a[1] = new
Object[] a = new Customer(); √
Object[10000]; a[0]

3) Arrays Concept is Not implemented based on Some Standard Data Structure Hence
Readymade Methods Support is Not Available. Hence for Every Requirement we have to
write the Code Explicitly which Increases Complexity of the Programming.

To Overcome Above Problems of Arrays we should go for Collections.

3DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Advantages Of Collections:

1) Collections are Growable in Nature. That is based on Our Requirement we canIncrease OR


Decrease the Size.
2) Collections can Hold Both Homogeneous and Heterogeneous Elements.
3) Every Collection Class is implemented based on Some Standard Data Structure.Hence for
Every Requirement Readymade Method Support is Available. Being a Programmer we have
to Use those Methods and we are Not Responsible to Provide Implementation

Differences Between Arrays And Collections:


Arrays Collections

Arrays are Fixed in Size. Collections are Growable in Nature.

With Respect to Memory Arrays are With Respect to Memory Collections are
Not Recommended to Use. Recommended to Use.

With Respect to Performance Arrays With Respect to Performance Collections are


are Recommended to Use. Not Recommended to Use.

Arrays can Hold Only Homogeneous Collections can Hold Both Homogeneous
Data Elements. and Heterogeneous Elements.

Arrays can Hold Both Primitives and Objects. Collections can Hold Only Objects but Not Primitives.

Arrays Concept is Not implemented based For every Collection class underlying Data
on Some Standard Data Structure. Hence Structure is Available Hence Readymade Method
Readymade Method Support is Not Support is Available for Every Requirement.
Available.

Collection:

If we want to Represent a Group of Individual Objects as a Single Entity then we should go for
Collection.

Collection Frame Work:

4DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

It defines Several Classes and Interfaces which can be used to Represent a Group of Objects as
a Single Entity.

JAVA C++

Collection Container
Collection Frame Work Standard Template Library (STL)

9 Key Interfaces Of Collection Framework:

1) Collection (I)
2) List (I)
3) Set (I)
4) SortedSet(I)
5) NavigableSet(I)
6) Queue(I)
7) Map(I)
8) SortedMap(I)
9) NavigableMap(I)

1) Collection (I):
∙ If we want to Represent a Group of Individual Objects as a Single Entity then we should
go for Collections.
∙ Collection Interface is considered as Root Interface of Collection Framework. ∙
Collection Interface defines the Most Common Methodswhich are Applicable for any
Collection Object.

Difference Between Collection (I) and Collections (C):

∙ Collection is an Interface which can be used to Represent a Group of Individual Objects as a


Single Entity.
∙ Whereas Collections is an Utility Class Present in java.util Package to Define Several Utility
Methods for Collection Objects.

Note: There is No Concrete Class which implements Collection Interface Directly.

5DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

2) List (I):
∙ 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 Preserved. Then we should go for
List.

Collection (I)
(1.2 V)

List (I)
(1.2 V)
(1.0 V)
Note: In 1.2 Version onwards Vector and Stack Classes are re-engineered to Implement List
Interface. 3) Set ArrayList (C) (C)
Vector (C) Stack

(I): (1.2 V)LinkedList


(C) (1.2 V)
Legacy Classes

∙ It is the Child Interface of the Collection.


∙ If we want to Represent a Group of Individual Objects as a Single Entity where
Duplicates are Not allowed and Insertion Order won't be Preserved. Then we should go
for Set Interface.

Collection (I)
(1.2 V)

Set (I)
(1.2 V)

HashSet (C)
(1.2 V)

LinkedHashSet (C)
(1.4 V)

4) SortedSet (I):
∙ It is the Child Interface of Set.
∙ If we want to Represent a Group of Individual Objects Without Duplicates According to
Some Sorting Order then we should go for SortedSet.

6DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

5) NavigableSet (I):
∙ It is the Child Interface of SortedSet.
∙ It defines Several Methods for Navigation Purposes.

Collection (I)
(1.2 V)
Set (I)
(1.2 V)

SortedSet (I)
(1.2 V)

NavigableSet (I)
(1.6 V)

TreeSet (C)
(1.2 V)

6) Queue (I):
∙ It is the Child Interface of Collection.
∙ If we want to Represent a Group of Individual Objects Prior to Processing then we
should go for Queue.

Eg: Before sending a Mail we have to Store All MailID’s in Some Data Structure and in which
Order we added MailID’s in the Same Order Only Mails should be delivered (FIFO). For this
Requirement Queue is Best Suitable.

Collection (I)
(1.2 V)

1.5 V
Queue (I)

PriorityQueue (C) BlockingQueue (C)

PriorityBlockingQueue LinkedBlockingQueue

Note:
∙ All the Above Interfaces (Collection, List , Set, SortedSet, NavigableSet,and Queue) Meant
for representing a Group of Individual Objects.
∙ If we want to Represent a Group of Key - Value Pairs then we should go for Map. 7)

Map (I):

7DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ Map is Not Child Interface of Collection.


∙ If we want to Represent a Group of Objects as Key- Value Pairs then we should go for
Map Interface.
∙ Duplicate Keys are Not allowed but Values can be Duplicated.
Dictionary (AC)
Map (I) (1.2 V)
1.0 V
(1.2 V) Properties
HashMap (I) IdentityHashMap
(1.2 V) (I) (1.4 V)
Hashtable
8) SortedMap
(I):
WeakHashMap (I)

∙ It is the Child Interface of Map.


∙ If we want to Represent a Group of Objects as Key- Value Pairs according to Some
Sorting Order of Keys then we should go for SortedMap.
∙ Sorting should be Based on Key but Not Based on Value.

8DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

9) NavigableMap (I):
∙ It is the Child Interface of SortedMap.
∙ It Defines Several Methods for Navigation Purposes.

Map (I)
(1.2 V)

SortedMap (I)
(1.2 V)
NavigableMap (I)
(1.6 V)
Note:In Collection Framework the following are Legacy Classes.
1) Enumeration TreeMap (I)
(I)
2) Dictionary (Abstract Class)
(1.6 V)
3) Vector (Concrete Class)
4) Stack (Concrete Class)
5) Hashtable (Concrete Class)
6) Properties (Concrete Class)

Map (I) p (I) (1.4 V) (1.2 V)


(1.2 V)
1.0 V
HashMap (I)
(1.2 V) Dictionary (AC)
WeakHashMap
(I) (1.2 V) IdentityHashMa SortedMap (I) Hashtable
NavigableMap (I) (1.6 V) (1.6 V)
Properties
LinkedHashMap (I) (1.4 V) TreeMap (I)

9DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
2) Arrays
1) Comparable (I)
Cursors 2) Comparator (I)
JAVA Means DURGA SIR
Utility Classes

1) Collections
Sorting
1) Enumeration (I)
2) Iterator (I)
3) ListIterator (I)

1) Collection Interface:

If we want to Represent a Group of Individual Objects as a Single Entity then we


should go for Collection Interface.

Methods:
∙ Collection Interface defines the Most Common Methods which are Applicable for any
Collection Objects.
∙ The following is the List of the Methods Present Inside Collection Interface.

1) boolean add(Object o)

2) booleanaddAll(Collection c)

3) boolean remove(Object o)

4) booleanremoveAll(Collection c)

5) booleanretainAll(Collection c): To Remove All Objects Except those Present in c.

6) void clear()

7) boolean contains(Object o)

8) booleancontainsAll(Collection c)

10 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
toArray() 12) Iterator

iterator()
9) booleanisEmpty()

10) int size() Note:


JAVA Means DURGA SIR
11) Object[]

∙ There is No Concrete Class which implements Collection Interface Directly. ∙


There is No Direct Method in Collection Interface to get Objects.

2) List:

∙ It is the Child Interface of Collection.


∙ If we want to Represent a Group of Individual Objects where Duplicates are allowed
and Insertion Order Preserved. Then we should go for List.
∙ We can Preserve Insertion Order and we can Differentiate Duplicate Object by using
Index. Hence Index will Play Very Important Role in List.

Methods:List Interface Defines the following Specific Methods.

1) void add(int index, Object o)

2) booleanaddAll(int index, Collection c)

3) Object get(int index)

4) Object remove(int index)

5) Object set(int index, Object new):To Replace the Element Present at specified Index
with provided Object and Returns Old Object.

6) intindexOf(Object o):Returns Index of 1st Occurrence of 'o'

7) intlastIndexOf(Object o)

8) ListIteratorlistIterator();

2.1) ArrayList:

∙ The Underlying Data Structure for ArrayList is Resizable Array ORGrowable Array. ∙
Duplicate Objects are allowed.
∙ Insertion Order is Preserved.
∙ Heterogeneous Objects are allowed (Except TreeSet and TreeMap Everywhere
Heterogeneous Objects are allowed).
∙ null Insertion is Possible.

Constructors:

11 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

1) ArrayList l = new ArrayList();

∙ Creates an Empty ArrayList Object with Default Initial Capacity 10. ∙ If ArrayList
Reaches its Max Capacity then a New ArrayList Object will be Created with
New Capacity = (Current Capacity * 3/2)+1

2) ArrayList l = new ArrayList(intinitialCapacity);


Creates an Empty ArrayList Object with specified Initial Capacity.

3) ArrayList l = new ArrayList(Collection c);


∙ Creates an EqualentArrayList Object for the given Collection Object. ∙
This Constructor Meant for Inter Conversion between Collection Objects.

importjava.util.ArrayList;
classArrayListDemo {
public static void main(String[] args){

ArrayList l = new ArrayList();

l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l); //[A, 10, A, null]

l.remove(2);
System.out.println(l); //[A, 10, null]

l.add(2,"M");
l.add("N");
System.out.println(l); //[A, 10, M, null, N]

}
}
∙ Usually we can Use Collections to Hold and Transfer Data (Objects) form One Location to
Another Location.

12 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ To Provide Support for this Requirement Every Collection Class Implements Serializable
and Cloneable Interfaces.
∙ ArrayList and Vector Classes Implements RandomAccess Interface. So that we can Access
any Random Element with the Same Speed.
∙ RandomAccess Interface Present in java.utilPackage and it doesn't contain any Methods.
Hence it is a Marker Interface.
∙ Hence ArrayList is Best Suitable if Our Frequent Operation is Retrieval Operation.

ArrayList l1 = new ArrayList();


LinkedList l2 = new LinkedList();

System.out.println(l1 instanceofSerializable); //true


System.out.println(l2 instanceofCloneable); //true
System.out.println(l1 instanceofRandomAccess); //true
System.out.println(l2 instanceofRandomAccess); //false

Differences between ArrayList and Vector:


ArrayList Vector

Every Method Present Inside Every Method Present in Vector


ArrayListis Non – Synchronized. is Synchronized.

At a Time Multiple Threads are allow At a Time Only One Thread is allow
to Operate on ArrayList to Operate on Vector Object and
Simultaneously and Hence ArrayList Hence Vector Object is Always
Object is Not Thread Safe. Thread Safe.

Relatively Performance is High Relatively Performance is Low


because Threads are Not required to because Threads are required to
Wait. Wait.
Introduced in 1.2 Version and it is Non Introduced in 1.0 Version and it is Legacy.
– Legacy.

How to get Synchronized Version of ArrayList Object?

13 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

By Default ArrayList Object is Non- Synchronized but we can get Synchronized Version
ArrayList Object by using the following Method of Collections Class.

public static List synchronizedList(List l)

ArrayListal = new ArrayList ();


Eg:
Synchronized Version
List l =
Non - Synchronized
Collections.synchroniz
Version
edList(al);

Similarly we can get Synchronized Version of Set and Map Objects by using the following
Methods of Collection Class.

public static Set synchronizedSet(Set s)

public static Map synchronizedMap(Map m)

∙ ArrayList is the Best Choice if we want to Perform Retrieval Operation Frequently. ∙ But ArrayList
is Worst Choice if Our Frequent Operation is Insertion OR Deletion in the Middle. Because
it required Several Shift Operations Internally.

2.2) LinkedList:

∙ The Underlying Data Structure is Double LinkedList.


∙ Insertion Order is Preserved.
∙ Duplicate Objects are allowed.
∙ Heterogeneous Objects are allowed.
∙ null Insertion is Possible.
∙ Implements Serializable and Cloneable Interfaces but Not RandomAccessInterface. ∙
Best Choice if Our Frequent Operation is InsertionOR Deletion in the Middle. ∙ Worst
Choice if Our Frequent Operation is Retrieval.

Constructors:

1) LinkedList l = new LinkedList(); Creates an Empty LinkedList Object.

2) LinkedList l = new LinkedList(Collection c);


Creates an Equivalent LinkedList Object for the given Collection.

Methods:
Usually we can Use LinkedList to Implement Stacks and Queues. To Provide Support for this
Requirement LinkedList Class Defines the following 6 Specific Methods.
1) void addFirst(Object o)
2) void addLast(Object o)
3) Object getFirst()
4) Object getLast()
5) Object removeFirst()

14 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

6) Object removeLast()

importjava.util.LinkedList;
classLinkedListDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Durga");
l.add(30);
l.add(null);
l.add("Durga");
l.set(0, "Software");
l.add(0,"Venky");
l.removeLast();
l.addFirst("CCC");
System.out.println(l); //[CCC, Venky, Software, 30, null]
}
}

2.3) Vector:
∙ The Underlying Data Structure is Resizable Array ORGrowable Array.
∙ Insertion Order is Preserved.
∙ Duplicate Objects are allowed.
∙ Heterogeneous Objects are allowed.
∙ null Insertion is Possible.
∙ Implements Serializable, Cloneable and RandomAccess interfaces.
∙ Every Method Present Inside Vector is Synchronized and Hence Vector Object is
Thread Safe.
∙ Vector is the Best Choice if Our Frequent Operation is Retrieval.
∙ Worst Choice if Our Frequent Operation is Insertion OR Deletion in the Middle.
Constructors:

1) Vector v = new Vector();

15 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ Creates an Empty Vector Object with Default Initial Capacity 10.


∙ Once Vector Reaches its Max Capacity then a New Vector Object will be Created with

New Capacity = Current Capacity * 2

2) Vector v = new Vector(intinitialCapacity);

3) Vector v = new Vector(intinitialCapacity, intincrementalCapacity);

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

Methods:

1) To Add Elements:
∙ add(Object o)Collection
∙ add(int index, Object o)List
∙ addElement(Object o) Vector

2) To Remove Elements:
∙ remove(Object o) Collection
∙ removeElement(Object o)Vector
∙ remove(int index) List
∙ removeElementAt(int index)Vector
∙ clear() Collection
∙ removeAllElements()Vector

3) To Retrive Elements:
∙ Object get(int index)List
∙ Object elementAt(int index)Vector
∙ Object firstElement() Vector
∙ Object lastElement()Vector

4) Some Other Methods:


∙ int size()
∙ int capacity()
∙ Enumeration element()
16 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.Vector;
classVectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.capacity()); //10
for(int i = 1; i<=10; i++) {
v.addElement(i);
}
System.out.println(v.capacity()); //10
v.addElement("A");
System.out.println(v.capacity()); //20
System.out.println(v); //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
}
}

2.3.1) Stack:

∙ It is the Child Class of Vector.


∙ It is a Specially Designed Class for Last In First Out (LIFO) Order.

Constructor:Stack s = new Stack();

Methods:

1) Object push(Object o); To Insert an Object into the Stack.


2) Object pop(); To Remove and Return Top of the Stack.
3) Object peek(); Ro Return Top of the Stack without Removal.
4) boolean empty(); Returns true if Stack is Empty
5) int search(Object o);Returns Offset if the Element is Available Otherwise Returns -1.

importjava.util.Stack;
classStackDemo {
public static void main(String[] args) { Stack s = new Stack(); s.push("A");
s.push("B"); }
s.push("C"); } 1
System.out.println(s);
Offset 1 CBA
//[A, B, C] 0
System.out.println(s.s
2 Index
earch("A")); //3
System.out.println(s.s
earch("Z")); //-1 3 2

17 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

The 3 Cursors of Java:

∙ If we want to get Objects One by One from the Collection then we should go for Cursors. ∙
There are 3 Types of Cursors Available in Java.
1) Enumeration
2) Iterator
3) ListIterator

1) Enumeration:
∙ We can Use Enumeration to get Objects One by One from the Collection. ∙
We can Create Enumeration Object by using elements().
public Enumeration elements();

Eg:Enumeration e = v.elements(); //v is Vector Object.

Methods:
1) public booleanhasMoreElements();
2) public Object nextElement();

importjava.util.*;
classEnumerationDemo {
public static void main(String[] args) {
Vector v = new Vector();
for(int i=0; i<=10; i++) { while(e.hasMoreElements()) {
v.addElement(i); Integer I = (Integer)e.nextElement();
} if(I%2 == 0)
System.out.println(v); System.out.println(I);
Enumeration e = v.elements(); }
System.out.println(v); 2
} 4
} 6
8
10
Limitations of Enumeration: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0

∙ Enumeration Concept is Applicable Only for Legacy Classes and it is Not a Universal
Cursor.
∙ By using Enumeration we can Perform Read Operation and we can't Perform Remove
Operation.

To Overcome Above Limitations we should go for Iterator.

18 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

2) Iterator:

∙ We can Use Iterator to get Objects One by One from Collection.


∙ We can Apply Iterator Concept for any Collection Object. Hence it is Universal Cursor. ∙
By using Iterator we can Able to Perform Both Read and Remove Operations. ∙ We can
Create Iterator Object by using iterator() of Collection Interface. public Iterator
iterator();

Eg:Iterator itr = c.iterator(); //c Means any Collection Object.

Methods:
1) public booleanhasNext()
2) public Object next()
3) public void remove()

importjava.util.*;
classIteratorDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
for (int i=0; i<=10; i++) {
l.add(i); if(I%2 == 0)
} System.out.println(I);
System.out.println(l); else
Iterator itr = l.iterator(); itr.remove();
while(itr.hasNext()) { }
Integer I = (Integer)itr.next(); System.out.println(l);
} 4
} 6
8
10
Limitations: [0, 2, 4, 6, 8, 10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 0
2

∙ By using Enumeration and Iterator we can Move Only towards Forward Direction and we
can’t Move Backward Direction. That is these are Single Direction Cursors but NotBi
Direction.
∙ By using Iterator we can Perform Only Read and Remove Operations and we can't Perform
Addition of New Objects and Replacing Existing Objects.

To Overcome these Limitations we should go for ListIterator.

19 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

3) ListIterator:

∙ ListIterator is the Child Interface of Iterator.


∙ By using ListIterator we can Move Either to the Forward Direction OR to the
Backward Direction. That is it is a Bi-Directional Cursor.
∙ By using ListIterator we can Able to Perform Addition of New Objects andReplacing
existing Objects. In Addition to Read and Remove Operations.
∙ We can Create ListIterator Object by using listIterator().
publicListIteratorlistIterator();

Eg:ListIteratorltr = l.listIterator(); //l is Any List Object

Methods:
∙ ListIteratoris the Child Interface of Iterator and Hence All Iterator Methods by Default
Available to the ListIterator.

Iterator (I)

ListIterator (I)

∙ ListIteratorDefines the following 9 Methods.


publicbooleanhasNext()
public Object next() add(Object new)
publicintnextIndex() Forward Direction Backward

publicbooleanhasPrevious
() public Object previous()
publicintpreviousIndex() Direction

public void remove()


public void set(Object
new) public void

20 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,  040 – 64 51 27
86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
if(s.equals("Naag"))
ltr.add("Chaitu");
if(s.equals("Chiru"))
ltr.add("Charan");
}
System.out.println(l);
}
}
JAVA Means DURGA SIR

importjava.util.*;
classListIteratorDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Baala");
l.add("Venki");
l.add("Chiru");
l.add("Naag");
System.out.println(l);
ListIteratorltr = l.listIterator();
while(ltr.hasNext()) {
String s = (String)ltr.next();
if(s.equals("Venki"))
ltr.remove();
[Baala, Chiru, Charan, Naag, Chaitu]

[Baala, Venki, Chiru, Naag]

Note: The Most Powerful Cursor is ListIterator. But its Limitation is, it is Applicable Only for
List Objects.

Comparison Table of 3 Cursors:

Property
En

Applicable For Any Collection


(Only Forward)
Only Legacy Classes
Bi-Direction
Objects

Single Direction

Movement Single Direction (Only Forward)


How To Get By using By using By using listIterator() of
iterator() List (I)

Accessability Only
Read and Read , Remove, Replace
Remove And

21 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

hasNext()
Methods next()
hasMoreElements() remove() 9 Methods
nextElement()

JAVA Means DURGA SIR


Add

Yes (1.0 Version) No (1.2 Version)


Is it legacy?

Internal Implementation of Cursors:

importjava.util.*;
classCursorDemo {
public static void main(String args[]) {
Vector v = new Vector();
Enumeration e = v.elements(); );
Iterator itr = v.iterator(); }
ListIteratorlitr = v.listIterator(); }
System.out.println(e.getClass().getName()); java.util.Vector$1 java.util.Vector$Itr
System.out.println(itr.getClass().getName()) java.util.Vector$ListItr
;
System.out.println(litr.getClass().getName()
22 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

3) Set:

∙ It is the Child Interface of Collection.


∙ 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.
∙ Set Interface doesn't contain any New Methods and Hence we have to Use Only
Collection Interface Methods

Collection (I)
(1.2 V)

Set (I)
3.1) HashSet:
(1.2 V)
SortedSet (I)
HashSet (C)
∙ The Underlying Data
Structure is Hashtable. (1.2 (1.2 V)
V)
∙ Insertion Order is Not Preserved and it isBased on hashCode of the Objects. ∙ Duplicate
Objects are Not Allowed. If we are trying to Insert Duplicate Objects then we
LinkedHashSet (C) NavigableSet (I)
won't get any Compile Time ORRuntime Error.add() Simply Returns false.
∙ null Insertion is Possible. allowed.
(1.4 V) (1.6 V)
∙ Heterogeneous objects are

∙ HashSet implements Serializable and Cloneable Interfaces but Not RandomAccess.


TreeSet (C)
∙ If Our Frequent Operation is Search Operation, then HashSet is the Best Choice.
(1.2 V)

Constructors:
1) HashSet h = new HashSet();
Creates an Empty HashSet Object with Default Initial Capacity 16 and Default Fill Ratio :
0.75.

2) HashSet h = new HashSet(intinitialCapacity);


Creates an Empty HashSet Object with specified Initial Capacity and Default Fill Ratio :
0.75.

3) HashSet h = new HashSet(intinitialCapacity, float fillRatio);

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

23 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Load Factor:

Fill Ratio 0.75 Means After Filling 75% Automatically a New HashSet Object will be Created.
This Factor is Called Fill RatioORLoad Factor.

importjava.util.*;
classHashSetDemo {
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);
3.1.1) LinkedHashSet:
System.out.println(h.add("Z")); //false
∙ It is the Child Class of HashSet.
System.out.println(h); //[null, D, B, C, 10, Z]
∙ It is Exactly Same as HashSet Except the following Differences.
}
}
The Underlying Data Structure
HashSet is Hashtable.
LinkedHashSet Combination of LinkedList and
Hashtable.
The Underlying Data Structure is a
Insertion Order is Not Preserved. Insertion Order will be Preserved.
Introduced in 1.2 Version. Introduced in 1.4 Version.

In the Above Example if we Replace HashSet with LinkedHashSet then Output is


false
[B, C, D, Z, null, 10]
That is Insertion Order is Preserved.
Note: In General we can UseLinkedHashSetandLinkedHashMapto Develop Cache Based
Applications where Duplicates are Not Allowed and Insertion Order Must be Preserved.

3.2) SortedSet:

∙ It is the Child Interface of Set.


∙ If we want to Represent a Group of Individual Objects without Duplicates and all
Objects will be Inserted According to Some Sorting Order, then we should go for
SortedSet.
∙ The Sorting can be Either Default Natural Sorting OR Customized Sorting Order. ∙
For String Objects Default Natural Sorting is Alphabetical Order. ∙ For Numbers
Default Natural Sorting is Ascending Order.

Methods:

1) Object first(); Returns 1st Element of the SortedSet.

2) Object last(); Returns Last Element of the SortedSet.

3) SortedSetheadSet(Object obj);
Returns SortedSet whose Elements are < Object.

4) SortedSettailSet(Object obj);
Returns SortedSet whose Elements are >= Object.
24 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

5) SortedSetsubSet(Object obj1, Object obj2);


Returns SortedSet whose Elements are >= obj1 and <obj2.

6) Comparator comparator();
▪ Returns Comparator Object that Describes Underlying SortingTechnique. ▪
If we are using Default Natural Sorting Order then we will get null.

SortedSet
2) last()  109 subset(101, 106)
Eg: 3) headSet(104)  [101, 103, 104]
100 101 103 104 [100, 101, 103] 4) 6) comparator() 
106 109 tailSet(104)  null
1) first()  100 [104, 106, 109] 5)

3.2.1.1) TreeSet:

∙ The Underlying Data Structure is Balanced Tree.


∙ Insertion Order is Not Preserved and it is Based on Some Sorting Order. ∙ Heterogeneous
Objects are Not Allowed. If we are trying to Insert we will get Runtime Exception Saying
ClassCastException.
∙ Duplicate Objects are Not allowed.
∙ null Insertion is Possible (Only Once).
∙ Implements Serializable and Cloneable Interfaces but Not RandomAccess Interface.

25 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

1) TreeSet t = new TreeSet();


JAVA Means DURGA SIR
Constructors:

Creates an Empty TreeSet Object where all Elements will be Inserted According to Default
Natural Sorting Order.

2) TreeSet t = new TreeSet(Comparator c);


Creates an Empty TreeSet Object where all Elements will be Inserted According to
Customized Sorting Order which is described by Comparator Object.

3) TreeSet t = new TreeSet(Collection c);

4) TreeSet t = new TreeSet(SortedSet s);

importjava.util.TreeSet;
classTreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add("A"); RE: Exception in thread "main"
t.add("a"); java.lang.ClassCastException:
t.add("B"); java.lang.String cannot be cast to
t.add("Z"); java.lang.Integer
t.add("L");
t.add(new Integer(10));

t.add(null);//RE: Exception in thread "main" java.lang.NullPointerException


System.out.println(t); //[A, B, L, Z, a]
}
}

null Acceptance:

∙ For Empty TreeSet as the 1st Element null Insertion is Possible. But after inserting that null if
we are trying to Insert any Element we will get NullPointerException.
∙ For Non- Empty TreeSet if we are trying to Insert null we will get NullPointerException.

importjava.util.TreeSet;
classTreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("L"));
t.add(new StringBuffer("B"));
System.out.println(t);
}
}

RE: Exception in thread "main" java.lang.ClassCastException:


java.lang.StringBuffer cannot be cast to java.lang.Comparable

26 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Note:

∙ If we are Depending on Default Natural Sorting Order Compulsory Objects should be


Homogeneous and Comparable. Otherwise we will get RE: ClassCastException. ∙ An
object is said to be Comparable if and only if corresponding class implements
Comparable interface.
∙ All Wrapper Classes, String Class Already Implements Comparable Interface. But
StringBuffer Class doesn't Implement Comparable Interface.
∙ Hence we are ClassCastException in the Above Example.

Comparable (I):

Comparable Interface Present in java.lang Package and it contains Only One Method
compareTo(). ect o);
publicintcompareTo(Obj

obj1.compareTo(obj2)
Returns –ve if and Only if obj1 has to Come Before obj2
Returns +ve if and Only if obj1 has to Come After obj2
Returns 0 if and Only if obj1 and obj2are Equal

System.out.println("A".compareTo("Z")); //-25
System.out.println("Z".compareTo("K")); //15
Eg:
System.out.println("Z".compareTo("Z")); //0
System.out.println("Z".compareTo(null)); //RE: java.lang.NullPointerException

Wheneverwe are Depending on Default Natural Sorting Order and if we are trying to Insert
Elements then Internally JVM will Call compareTo() to IdentifySorting Order.

TreeSet t = new TreeSet();


t.add(“K”); √
+ ve
t.add(“Z”); “Z”.compateTo(“K”);
Eg: t.add(null);
- ve
t.add(“A”); NullPointerException
“A”.compateTo(“K”);
System.out.println(t);
0
t.add(“A”); [A, K, Z]

“A”.compateTo(“A”);

Note: If we are Not satisfied with Default Natural Sorting Order OR if Default Natural
Sorting Order is Not Already Available then we can Define Our Own Sorting by using
Comparator Object.

Comparable Meant for Default Natural Sorting Order whereas


Comparator Meant for Customized Sorting Order

27 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Comparator (I):

This Interface Present in java.util Package.

Methods: It contains 2 Methodscompare() and equals().

publicint compare(Object obj1, Object obj2);


Returns –ve if and Only if obj1 has to Come Before obj2.
Returns +ve if and Only if obj1 has to Come After obj2.
Returns 0 if and Only if obj1 and obj2 are Equal.

publicboolean equals(Object o);

Whenever we are implementing Comparator Interface


Compulsory we should Provide Implementation for compare().
Implementing equals() is Optional because it is Already
Available to Our Class from Object Class through Inheritance.

Write a Program to Insert Integer Objects into the TreeSet where Sorting Order is Descending
Order:
28 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.*;
classTreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator()); 1
t.add(10);
t.add(0); compare(0,10);+1
t.add(15); compare(15,10);-1
t.add(5); compare(5,15); +ve
compare(5,10); +1
compare(5,0); -1
t.add(20); compare(20,15); -1
t.add(20); compare(20,20); 0
System.out.println(t);//[20, 15, 10, 5, 0]
}
}
classMyComparator implements Comparator {
publicint compare(Object obj1, Object obj2) {
Integer i1 = (Integer)obj1;
Integer i2 = (Integer)obj2;
if(i1 < i2)
return +1;
else if(i1 > i2)
return -1;
else
return 0;
}
}

∙ At Line 1 if we are Not Passing Comparator Object as an Argument then Internally JVM
will Call compareTo(). Which is Meant for Default Natural Sorting Order (Ascending
Order). In this Case the Output is [0, 5, 10, 15, 20].
∙ At Line 1 if we are Passing Comparator Object then JVM will Call compare() Instead of
compareTo(). Which is Meant for Customized Sorting (Descending Order). In this Case the
Ouput is [20, 15, 10, 5, 0].

Various Possible Implementations of compare():

publicint compare(Object obj1, Object obj2) {


Integer I1 = (Integer)obj1;
Integer I2 = (Integer)obj2;
return I1.compareTo(I2); //[0, 5, 10, 15, 20] Ascending Order
return -I1.compareTo(I2); //[20, 15, 10, 5.0] Descending Order
return I2.compareTo(I1); //[20, 15, 10, 5.0]
return -I2.compareTo(I1); //[0, 5, 10, 15, 20]
return +1; //[10, 0, 15, 5, 20, 20] Insertion Order
return -1; //[20, 20, 5, 15, 0, 10] Reverse of Insertion Order
return 0; //[10] Only 1st Inserted Element Present And All Remaining Elements Treated as Duplicates
}

Write a Program to Insert String Objects into the TreeSet where the Sorting Order is of
Reverse of Alphabetical Order:

29 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.*;
importjava.util.*;
classTreeSetDemo {
classTreeSetDemo {
public static void main(String[] args) {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator());
TreeSet t = new TreeSet(new MyComparator());
t.add("Roja");
t.add("Roja");
t.add("Sobha Rani");
t.add("Sobha Rani");
t.add("Raja Kumari");
t.add("Raja Kumari");
t.add("Ganga Bhavani");
t.add("Ganga Bhavani");
t.add("Ramulamma");
t.add("Ramulamma");
System.out.println(t);
System.out.println(t);
}
}
}
}
classMyComparator implements Comparator {
classMyComparator implements Comparator {
publicint compare(Object obj1, Object obj2) {
publicint compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s1 = obj1.toString();
String s2 = (String)obj2;
String s2 = (String)obj2;
return s2.compareTo(s1);//[Sobha Rani, Roja, Ramulamma, Raja Kumari, Ganga Bhavani]
return s2.compareTo(s1);//[Sobha Rani, Roja, Ramulamma, Raja Kumari, Ganga
Bhavani] //return -s1.compareTo(s2);//valid
//return -s1.compareTo(s2); //Valid
}
}
}
}

30 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Write a Program to Insert StringBuffer Objects into the TreeSet where Sorting Order is
Alphabetical Order:
importjava.util.*;
classTreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator1());
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t);
}
}
class MyComparator1 implements Comparator {
publicint compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s1.compareTo(s2); //[A, K, L, Z]
}
}

Write a Program to Insert String and StringBuffer Objects into the TreeSet where Sorting
Order is Increasing Length Order. If 2 Objects having Same Length then Consider their
Alphabetical Order:

importjava.util.*;
classTreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator());
t.add("A");
t.add(new StringBuffer("ABC"));
t.add(new StringBuffer("AA"));
t.add("XX");
t.add("ABCE");
t.add("A");
System.out.println(t);
}
}
classMyComparator implements Comparator {
publicint compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
int i1 = s1.length();
int i2 = s2.length();
if(i1 < i2)return -1;
else if(i1 > i2)return 1;
elsereturn s1.compareTo(s2); //[A, AA, XX, ABC, ABCE]
}
}

31 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Note:
∙ If we are Depending on Default Natural Sorting Order Compulsory Objects should be
Homogeneous and Comparable Otherwise we will get RE: ClassCastException. ∙ If we
defining Our Own Sorting by Comparator then Objects Need Not be Homogeneous and
Comparable. That is we can Add Heterogeneous Non Comparable Objects to the TreeSet.

When we go for Comparable and When we go for Comparator:


Comparable Vs Comparator:

∙ For Predefined Comparable Classes (Like String) Default Natural Sorting Order is Already
Available. If we are Not satisfied with that we can Define Our Own Sorting by Comparator
Object.
∙ For Predefine Non- Comparable Classes (Like StringBuffer) Default Natural Sorting Order is
Not Already Available. If we want to Define Our Own Sorting we can Use Comparator
Object.
∙ For Our Own Classes (Like Employee) the Person who is writing Employee Class he is
Responsible to Define Default Natural Sorting Order by implementing Comparable
Interface.
∙ The Person who is using Our Own Class if he is Not satisfied with Default Natural Sorting
Order he can Define his Own Sorting by using Comparator Object.
∙ If he is satisfied with Default Natural Sorting Order then he can Use Directly Our Class.
Our Own Classes
(Employee)
Predefined Comparable
Comparator Comparator
Classes Comparable (DNSO) Based on
(String) Who is writing
eid
Predefined Who is Using this
this Class Comparator Based on name
Non - Comparable Classes
Class
(StringBuffer)

32 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Write a Program to Insert Employee Objects into the TreeSet where DNSO is Based on
Ascending Order of EmployeeId and Customized Sorting Order is Based on Alphabetical Order
of Names:

importjava.util.*;
class Employee implements Comparable {
String name;
inteid;
Employee(String name, inteid) {
this.name = name;
this.eid = eid;
}
public String toString() { return name+"-----"+eid;}
publicintcompareTo(Object obj) {
int eid1 = this.eid;
Employee e = (Employee)obj;
int eid2 = e.eid;
if(eid1 < eid2) return -1;
else if(eid1 > eid2) return 1;
else return 0;
}
}
classCompComp {
public static void main(String[] args) {
Employee e1 = new Employee("Nag", 100);
Employee e2 = new Employee("Bala", 200);
Employee e3 = new Employee("Chiru", 50);
Employee e4 = new Employee("Venki", 150);
Employee e5 = new Employee("Nag", 100);
TreeSet t = new TreeSet();
t.add(e1);
t.add(e2);
t.add(e3);
t.add(e4);
t.add(e5);
System.out.println(t);
TreeSet t1 = new TreeSet(new MyComparator());
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1);
}
}
classMyComparator implements Comparator {
Comparison of Comparable and Comparator:
publicint compare(Object obj1, Object obj2) {
Employee e1 = (Employee) obj1;
Comparable Comparator
Employee e2 = (Employee

Present in java.lang Package String s1 = Present in java.util Package


e1.name;

It is Meant for Default Natural Sorting It is Meant for Customized Sorting Order.
String s2 = e2.name;

return s1.compareTo(s2);
DURGASOFT, # 202,2nd
33 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,

}[Chiru-----50, Nag-----100, Venki-----150, Bala-----200]


 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
[Bala-----200, Chiru-----50, Nag-----100, Venki-----150]
JAVA Means DURGA SIR
Order.

Defines Only One Method compareTo(). Defines 2 Methods compare() and equals().

All Wrapper Classes and String The Only implemented Classes of


Class implements Comparable Comparator are Collator and
Interface. RuleBaseCollator.

Comparison Table of Set implemented Classes:


Property HashSet LinkedHashSet TreeSet

Underlying Data Hashtable Hashtable and Balanced Tree


Structure LinkedList

Insertion Order Not Preserved Preserved Not Preserved

Sorting Order Not Not Applicable Applicable


Applicable

Heterogeneous Objects Allowed Allowed Not Allowed

Duplicate Objects Not Allowed Not Allowed Not Allowed

null Acceptance Allowed Allowed (Only Once) For Empty TreeSet as the
(Only 1st Element null Insertion
Once) is Possible. In all Other
Cases we will get
NullPointerException.

Map
(1.2 V)
WeakHashMap 1.0 V
(I) (1.2 V) Dictionary (AC)
Map (I) IdentityHashMa
(1.2 V) p (I) (1.4 V) Hashtable
SortedMap (I)
(1.2 V)
HashMap (I)
NavigableMap (I) (1.6 V)

LinkedHashMap (I) TreeMap (I)


(1.4 V) (1.6 V)
Properties

∙ Map is Not Child Interface


of Collection.
∙ If we want to Represent a Group of Objects as Key- Value Pairs then we should go for Map. ∙
Both Keys and Values are Objects Only.
∙ Duplicate Keys are Not allowed. But Values can be Duplicated.
∙ Each Key- Value Pair is Called an Entry.

Key Value
101 Durga
Entry

Key Value
DURGASOFT, # 202,2nd
34 Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
102 Ravi
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
103 Pawan
104 NaNa
JAVA Means DURGA SIR

Methods

Map Interface Defines the following Methods

1) Object put(Object key, Object value);


To Add One Key- Value Pair.If the specified Key is Already Available then Old Value will
be Replaced with New Value and Returns Old Value.

2) void putAll(Map m)

3) Object get(Object key)

4) Object remove(Object key)

5) booleancontainsKey(Object key)

6) booleancontainsValue(Object value)
7) booleanisEmpty()

8) int size()

9) void clear()

10) Set keySet()


Entry (I):
11) Collection values()
Collection Views of Map
12) Set entrySet()

∙ Each Key- Value Pair is Called One Entry.


∙ Without existing Map Object there is No Chance of existing Entry Object. ∙
Hence Interface Entry is Define Inside Map Interface.

35 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

interface Map{
interface Entry{
Object getKey()
Object getValue()
Object setValue(Object new)
}
}
HashMap:

∙ The Underlying Data Structure is Hashtable.


∙ Duplicate Keys are Not Allowed. But Values can be Duplicated.
∙ Heterogeneous Objects are allowed for Both Keys and Values.
∙ Insertion Order is not preserved and it is based on hash code of the keys. ∙ null Insertion
is allowed for Key (Only Once) and allowed for Values (Any Number of Times)

Differences between and HashMap and Hashtable:


HashMap Hashtable

No Method Present in HashMap Every Method Present in Hashtable


is Synchronized. is Synchronized.

At a Time Multiple Threads are allowed At a Time Only One Thread is allowed
to Operate on HashMap Object to Operate on the Hashtable Object
simultaneously and Hence it is Not and Hence it is Thread Safe.
Thread Safe.

Relatively Performance is High. Relatively Performance is Low.

null is allowed for Both Keys and Values. null is Not allowed for Both Keys
and Values. Otherwise we will get
NPE.

Introduced in 1.2 Version and it Introduced in 1.0 Version and it is Legacy.


is Non – Legacy.

How to get Synchronized Version of HashMap:

By Default HashMap is Non- Synchronized. But we can get Synchronized Version of HashMap
by using synchronizedMap() of Collections Class.

Constructors:

1) HashMap m = new HashMap();


Creates an Empty HashMap Object with Default Initial Capacity 16 and Default Fill Ratio
0.75

2) HashMap m = new HashMap(intinitialcapacity);

3) HashMap m = new HashMap(intinitialcapacity, float fillRatio);

4) HashMap m = new HashMap(Map m);

36 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.*;
classHashMapDemo {
public static void main(String[] args) {
HashMap m = new HashMap();
m.put("Chiru", 700);
m.put("Bala", 800);
m.put("Venki", 200);
m.put("Nag", 500);
System.out.println(m);
System.out.println(m.put("Chiru", 1000));
Set s = m.keySet();
System.out.println(s);
Collection c = m.values();
System.out.println(c);
Set s1 = m.entrySet();
System.out.println(s1);
Iterator itr = s1.iterator();
while(itr.hasNext()) {
Map.Entry m1 = (Map.Entry)itr.next();
System.out.println(m1.getKey()+"....."+m1.getValue());
if(m1.getKey().equals("Nag")) {
m1.setValue(10000);
}
}
System.out.println(m);
}
}

{Chiru=700, Venki=200, Nag=500, Bala=800}


700
[Chiru, Venki, Nag, Bala]
[1000, 200, 500, 800]
[Chiru=1000, Venki=200, Nag=500, Bala=800]
Chiru.....1000
Venki.....200
Nag.....500
Bala.....800
{Chiru=1000, Venki=200, Nag=10000, Bala=800}

37 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

LinkedHashMap:

∙ It is the Child Class of HashMap.


∙ It is Exactly Same as HashMap Except the following Differeces.
HashMap LinkedHashMap
The Underlying Data
The Underlying Data Structure is
Structure is Hashtable.
Combination of Hashtable and LinkedList.
Insertion is Not Preserved. Insertion Order is Preserved.
Introduced in 1.2 Version. Introduced in 1.4 Version.

In the Above Example if we Replace HashMap with LinkedHashMap then Output is

{Chiru=700, Bala=800, Venki=200, Nag=500}


700
[Chiru, Bala, Venki, Nag]
[1000, 800, 200, 500]
[Chiru=1000, Bala=800, Venki=200, Nag=500]
Chiru.....1000
Bala.....800
Venki.....200
Nag.....500
{Chiru=1000, Bala=800, Venki=200, Nag=10000}
That is Insertion Order is Preserved.

Note: In General we can Use LinkedHashSet and LinkedHashMap for developing Cache Based
Applications where Duplicates are Not Allowed. But Insertion Order Must be Preserved.

IdentityHashMap:

It is Exactly Same as HashMap Except the following Difference.


∙ In HashMap JVM will Use .equals() to Identify Duplicate Keys, which is Meant for
ContentComparision.
∙ In IdentityHashMap JVM will Use == Operator to Identify Duplicate Keys, which is Meant
for Reference Comparison.

importjava.util.HashMap;
classIdentityHashMapDemo {
public static void main(String[] args) {
HashMap m = new HashMap();
Integer I1 = new Integer(10);
Integer I2 = new Integer(10);
m.put(I1,"Pawan");
m.put(I2,"Kalyan");
System.out.println(m); //{10=Kalyan}
}
}

38 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

If we Replace HashMap with IdentityHashMap in the Above Application then Output is


{10=Pawan, 10=Kalyan}.
Because I1 and I2 are Not Duplicate as I1 == I2 Returns false.

What is the Difference between == Operator and .equls()?


In General we can Use == Operator for Reference Comparison whereas .equals() for Content
Comparison.

Integer I1 = new Integer(10);


10
Integer I2 = new Integer(10);
I1
System.out.println(I1== I2);//false
10
I2
System.out.println(I1.equals(I2));//true

WeakHashMap:

It is Exactly Same as HashMap Except the following Difference.


∙ In Case of HashMap, HashMap Dominates Garbage Collector. That is if Object doesn’t
have any Reference Still it is Not Eligible for Garbage Collector if it is associated with
HashMap.
∙ But In Case of WeakHashMap if an Object doesn't contain any References then it is Always
Eligible for GC Even though it is associated with WeakHashMap. That is Garbage Collector
Dominates WeakHashMap.
importjava.util.HashMap;
classWeakHashMapDemo {
public static void main(String[] args) throws InterruptedException {
HashMap m = new HashMap();
Temp t = new Temp();
m.put(t, "Durga");
System.out.println(m);
t = null;
System.gc();
Thread.sleep(5000);
System.out.println(m);
}
}
class Temp {
public String toString() {
return "temp";
}
public void finalize() {
System.out.println("finalize() Called");
}

}{temp=Durga}
{temp=Durga}

If we ReplaceHashMap with WeakHashMap then the Output is

{temp=Durga}
finalize() Called
{}

SortedMap:
39 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ It is the Child Interface of Map.

∙ If we want to Represent a Group of Key - Value Pairs According Some Sorting Order of
Keys then we should go for SortedMap.

Methods:
SortedMapDefines the following Specific Methods.

1) Object firstKey();
2) Object lastKey();
3) SortedMapheadMap(Object key)
4) SortedMaptailMap(Object key)
5) SortedMapsubMap(Object key1, Object key2)
6) Comparator comparator()

TreeMap:

The Underlying Data Structure is Red -Black Tree.


Duplicate Keys are Not Allowed. But Values can be Duplicated.
Insertion Order is Not Preserved and it is Based on Some Sorting Order of Keys. If we are
depending on Default Natural Sorting Order then the Keys should be Homogeneous and
Comparable. Otherwise we will get Runtime Exception Saying ClassCastException. If we
defining Our Own Sorting by Comparator then Keys can be Heterogeneous and Non
Comparable.
But there are No Restrictions on Values. They can be Heterogeneous and Non-

Comparable. null Acceptance:

∙ For Empty TreeMap as the 1st Entry with null Key is Allowed. But After inserting that
Entry if we are trying to Insert any Other Entry we will get RE: NullPointerException. ∙
For Non- Empty TreeMap if we are trying to Insert null Entry then we will get Runtime
Exception Saying NullPointerException.
∙ There are No Restrictions on null Values.

40 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Constructors:

1) TreeMap t = new TreeMap(); For Default Natural Sorting Order.

2) TreeMap t = new TreeMap(Comparator c); For Customized Sorting Order. 3)

TreeMap t = new TreeMap(SortedMap m); Inter Conversion between Map Objects. 4)

TreeMap t = new TreeMap(Map m);


Example on Natural Sorting:

importjava.util.TreeMap;
class TreeMapDemo {
public static void main(String[] args) {
TreeMap m = new TreeMap();
m.put(100, "ZZZ"); m.put(103, java.lang.ClassCastException:
"YYY"); m.put(101, "XXX"); java.lang.Integer cannot be cast to
m.put(104, 106); m.put(107, null); java.lang.String
m.put("FFF", "XXX");
//RE: Exception in thread "main"

m.put(null, "XXX"); //RE: Exception in thread "main"


java.lang.NullPointerException System.out.println(m); //{100=ZZZ, 101=XXX,
103=YYY, 104=106, 107=null}
}
}

Example on Customized Sorting:

importjava.util.*;
class TreeMapDemo {
public static void main(String[] args) {
41 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
TreeMap m = new TreeMap(new MyComparator());
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Hashtable:

∙ The Underlying Data Structure for Hashtable is Hashtable Only.


∙ Duplicate Keys are Not Allowed. But Values can be Duplicated.
∙ Insertion Order is Not Preserved and it is Based on Hashcode of the Keys. ∙
Heterogeneous Objects are Allowed for Both Keys and Values.
∙ null Insertion is Not Possible for Both Key and Values. Otherwise we will get Runtime
Exception Saying NullPointerException.
∙ Every Method Present in Hashtable is Synchronized and Hence Hashtable Object is Thread
Safe.

Constructors:
1) Hashtable h = new Hashtable();
Creates an Empty Hashtable Object with Default Initial Capacity 11 and
Default Fill Ratio 0.75.

2) Hashtable h = new Hashtable(intinitialcapacity);


3) Hashtable h = new Hashtable(intinitialcapacity, float fillRatio);
4) Hashtable h = new Hashtable(Map m);

42 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.Hashtable;
classHashtableDemo {
public static void main(String[] args) {
Hashtable h = new Hashtable();
h.put(new Temp(5), "A");
h.put(new Temp(2), "B");
h.put(new Temp(6), "C");
h.put(new Temp(15), "D");
h.put(new Temp(23), "E");
h.put(new Temp(16), "F");
9
int i;
}
Properties: 8
h.put("Durga",null); //RE: Temp(int i) {
java.lang.NullPointerException
System.out.println(h); //{6=C, 16=F,
5=A, 15=D, 2=B, 23=E} } ∙ It is the Child Class of Hashtable. 7
this.i = i;

10 From Top To Bottom


class Temp {
∙ In Our Program if anything which Changes Frequently (Like Database User Name,
6 6=C
Password, Database URLs Etc) Never Recommended to Hard Code in Java Program.
} From Right To Left
5 5 = A, 16 = F
Because for Every Change in Source File we have to Recompile, Rebuild and Redeploying
publicinthashCod
e() { 4
Application and Sometimes Server Restart Also Required, which Creates Business Impact to the
Client. } 3
return i; 15 = D
∙ To Overcome this Problem we have to Configure Such Type of Propertiesin Properties File.
2 {
public String toString() 2 = B
∙ The Main Advantage in this Approach is if a there is a Change in Properties File, to Reflect
return i+""; 1 23 = E
that Change Just Redeployment is Enough, which won't Create any Business Impact.
} 0
∙ We can Use Properties Object to Hold Properties which are coming from Properties File. }
∙ Properties can be used to Represent a Group of Key – Value Pairs where Both Key and
Value should be String Type.

Constructor:Properties p = new Properties();

Methods:
43 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR
1) public String getProperty(String pname);
To Get the Value associated with specified Property.

2) public String setProperty(String pname, String pvalue);


To Set a New Property.

3) public Enumeration propertyNames();It Returns All Property Names.

4) public void load(InputStream is);


To Load Properties from Properties File into Java Properties Object.

5) public void store(OutputStreamos, String comment);


To Store Properties from Java Properties Object into Properties File.

load()

Properties File
classPropertiesDe
mo {
Java Properties importjava.util.Pro store()
Object perties; import
java.io.*; abc.properties
After Executing Properties File
FileOutputStreamfos = new
FileOutputStream("abc.properties"); #Updated by
Durga for SCJP Class
p.store(fos, "Updated by Durga for SCJP Class");
#Wed May 20 08:23:37 IST 2015
public static void main(String[] args) throws
}
Exception {
Properties p = new Properties(); }{Venki=9999;, Password=Tiger, User=Name: Scott}
FileInputStreamfis = new
FileInputStream("abc.properties"); Venki=9999;
p.load(fis);
System.out.println(p);
String s = p.getProperty("Venki"); abc.properties
System.out.println(s);
User Name: Scott Password: Tiger Venki = 9999;
p.setProperty("Nag", "88888");
Nag=88888
User=Name\:
Scott
9999;

Password=Tiger
44 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,  040 – 64 51 27
86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Eg: Pseudo Code

importjava.util.*;
import java.io.*;
classPropertiesDemo {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
FileInputStreamfis = new FileInputStream("db.properties");
p.load(fis);
String url = p.getProperty("url");
String user = p.getProperty("user");
String pwd = p.getProperty("pwd");
Connection con = DriverManager.getConnection(url,user,pwd);
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
}

1.5 Version Enhancements (Queue Interface):

∙ Queue is a Child Interface of Collection.


∙ If we want to Represent a Group of Individual Objects Prior to processing then we should
go for Queue.
∙ From 1.5 Version onwards LinkedListalso implements Queue Interface. ∙ Usually Queue
follows FIFO Order. But Based on Our Requirement we can Implement Our Own Priorities
Also (PriorityQueue)
∙ LinkedList based Implementation of Queue always follows FIFO Order.

Eg: Before sending a Mail we have to Store all Mail IDs in Some Data Structure and for the
1st Inserted Mail ID Mail should be Sent 1st.For this Requirement Queue is the Best Choice.

Methods:

45 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

1) boolean offer(Object o); To Add an Object into the Queue.

2) Object peek();
▪ To Return Head Element of the Queue.
▪ If Queue is Empty then this Method Returns null.

3) Object element();
▪ To Return Head Element of the Queue.
▪ If Queue is Empty then this Methodraises RE: NoSuchElementException

4) Object poll();
▪ To Remove and Return Head Element of the Queue.
▪ If Queue is Empty then this Method Returns null.

5) Object remove();
▪ To Remove and Return Head Element of the Queue.
▪ If Queue is Empty then this Method raise RE: NoSuchElementException.

PriorityQueue:

∙ This is a Data Structure which can be used to Represent a Group of Individual Objects
Prior to processing according to Some Priority.
∙ The Priority Order can be Either Default Natural Sorting Order OR Customized Sorting
Order specified by Comparator Object.
∙ If we are Depending on Natural Sorting Order then the Objects should be Homogeneous
and Comparable otherwise we will get ClassCastException.
∙ If we are defining Our Own Sorting by Comparator then the Objects Need Not
beHomogeneous and Comparable.
∙ Duplicate objects are Not Allowed.
∙ Insertion Order is Not Preserved and it is Based on Some Priority.
∙ null Insertion is Not Possible Even as 1st Element Also.
46 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,  040 – 64 51 27 86,
80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Constructors:

1) PriorityQueue q = new PriorityQueue();


Creates an Empty PriorityQueue with Default Initial Capacity 11 and all
Objects will be Inserted according to Default Natural Sorting Order.

2) PriorityQueue q = new PriorityQueue(intinitialcapacity);


3) PriorityQueue q = new PriorityQueue(intinitialcapacity, Comparator c);
4) PriorityQueue q = new PriorityQueue(SortedSet s);
5) PriorityQueue q = new PriorityQueue(Collection c);
importjava.util.PriorityQueue;
classPriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue();
System.out.println(q.peek()); //null
System.out.println(q.element()); //
java.util.NoSuchElementException for(int i=0; i<=10; i++) {
q.offer(i);
}
System.out.println(q); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(q.poll()); //0
System.out.println(q); //[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]
}
}

Note: Some Operating Systems won't Provide Proper Support for PriorityQueues.

importjava.util.*;
classPriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue q = new PriorityQueue(15, new MyComparator());
q.offer("A");
q.offer("Z");
q.offer("L");
q.offer("B");
System.out.println(q); //[Z, B, L, A]
}
}
classMyComparator implements Comparator {
publicint compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}

47 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

1.6 Version Enhancements:

NavigableSet (I):It is the Child Interface of SortedSet.

Collection (I)
(1.2 V)

Set (I)
(1.2 V)
SortedSet (I)
(1.2 V)

NavigableSet (I)
(1.6 V)

TreeSet (C)
(1.2 V)

Methods:It Defines Several Methods for Navigation Purposes.

1) floor(e); It Returns Highest Element which is <=e.

2) lower(e); It Returns Highest Element which is <e.

3) ceiling(e); It Returns Lowest Element which is >=e.

4) higher(e); It Returns Lowest Element which is >e.

5) pollFirst(); Remove and Return 1st Element.


6) pollLast(); Remove and Return Last Element.

7) descendingSet(); It Returns NavigableSet in Reverse Order.

48 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
SortedMap. Methods:

1) floorKey(e)
2) lowerKey(e)
3) ceilingKey(e)
importjava.util.TreeSet; 4) higherKey(e)
classNavigableSetDemo { 5) pollFirstEntry()
public static void main(String[] args) { 6) pollLastEntry()
TreeSet<Integer> t = new TreeSet<Integer>(); 7) descendingMap()
t.add(1000); JAVA Means DURGA SIR
t.add(2000);
t.add(3000);
t.add(4000);
t.add(5000);
System.out.println(t);
System.out.println(t.ceiling(2000));
System.out.println(t.higher(2000));
System.out.println(t.floor(3000));
System.out.println(t.lower(3000));
System.out.println(t.pollFirst()); [1000, 2000, 3000, 4000, 5000] 2000
System.out.println(t.pollLast()); 3000
System.out.println(t.descendingSet()); 3000
System.out.println(t); 2000
} 1000
} 5000
[4000, 3000, 2000]
[2000, 3000, 4000]
NavigableMap:It is the Child Interface of
49 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.TreeMap;
classNavigableMapDemo {
public static void main(String[] args) {
t.put("g", "Gun");

System.out.println(t);
System.out.println(t.ceilingKey("c"));
System.out.println(t.higherKey("e"));
System.out.println(t.floorKey("e"));
System.out.println(t.lowerKey("e"));
System.out.println(t.pollFirstEntry());
System.out.println(t.pollLastEntry());
System.out.println(t.descendingMap());
System.out.println(t);

}
}

Utility Classes

☀ Collections ☀ Arrays
{a=Apple, b=Banana, c=Cat, d=Dog, g=Gun}
Collections (C): c
TreeMap<String, String> t = new TreeMap<String, g
String>(); d
d
t.put("b", "Banana"); a=Apple
t.put("c", "Cat"); g=Gun
t.put("a", "Apple"); {d=Dog, c=Cat, b=Banana}
t.put("d", "Dog"); {b=Banana, c=Cat, d=Dog}

Collections Class is an Utility Class Present in java.util Package to Define Several Utility
Methods for Collection Objects.

☀ To Sort Elements of List:


Collections Class Defines the following Methods for this Purpose.

1) public static void sort(List l);


▪ To Sort Based on Default Natural Sorting Order.
▪ In this Case Compulsory List should contain Only Homogeneous andComparable
Objects. Otherwise we will get Runtime Exception Saying ClassCastException. ▪ List
should Not contain null Otherwise we will get NullPointerException.

2) public static void sort(List l, Comparator c);


To Sort Based on Customized Sorting Order.
50 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Program: To Sort Elements of List According to Natural Sorting Order

importjava.util.*;
classCollectionsSortDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("Z"); RE: Exception in thread "main"
al.add("A"); java.lang.ClassCastException:
al.add("K"); java.lang.String cannot be cast to
al.add("N"); java.lang.Integer
al.add(new Integer(10));

al.add(null); //RE: Exception in thread "main" java.lang.NullPointerException


System.out.println("Before Sorting:"+al); //Before Sorting:[Z, A, K, N]
Collections.sort(al);
System.out.println("After Sorting:"+al); //After Sorting:[A, K, N, Z]
}
}

Program: To Sort Elements of List According to Customized Sorting Order

importjava.util.*;
classCollectionsSortDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("Z");
al.add("A");
al.add("K");
al.add("N");
System.out.println("Before Sorting:"+al); //Before Sorting:[Z, A, K, N]
Collections.sort(al, new MyComparator());
System.out.println("After Sorting:"+al); //After Sorting: [Z, N, K, A]
}
}
classMyComparator implements Comparator {
publicint compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}

☀ Searching Elements of List:

1) public static intbinarySearch(List l, Object target);


If we are Sorting List According to Natural Sorting Order then we have to Use this Method.

2) public static intbinarySearch(List l, Object target, Comparator c); If we are


Sorting List according to Comparator then we have to Use this Method.
51 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Conclusions:

❖ Internally the Above Search Methods will Use Binary Search Algorithm. ❖ Before
performing Search Operation Compulsory List should be Sorted. Otherwise we will get
Unpredictable Results.
❖ Successful Search Returns Index.
❖ Unsuccessful Search Returns Insertion Point.
❖ Insertion Point is the Location where we can Insertthe Target Element in the SortedList. ❖ If
the List is Sorted according to Comparator then at the Time of Search Operation Also we
should Pass the Same Comparator Object. Otherwise we will get Unpredictable Results.

Program: To Search Elements of List According to Natural Sorting Order

importjava.util.*;
classCollectionsSearchDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("Z"); al.add("A"); AKMZa
al.add("M"); al.add("K");
01234
al.add("a"); al
-1 -2 -3 -4 -5

System.out.println(al); //[Z, A, M, K, a]
Collections.sort(al);
System.out.println(al); //[A, K, M, Z, a]
System.out.println(Collections.binarySearch(al, "Z")); //3
System.out.println(Collections.binarySearch(al, "J")); //-2
}
}
52 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Program: To Search Elements of List According to Customized Sorting Order

importjava.util.*;

classCollectionsSearchDemo { al.add(20);
public static void main(String args[]) { al.add(10);
ArrayList al = new ArrayList(); al.add(5);
System.out.println(al); //[15, 0, 20, 10, 5]
Collections.sort(al, new MyComparator());
System.out.println(al); //[20, 15, 10, 5, 0]
al -1 -2 -3 -4 -5 20 15 10 5 0 0 1 2 3 4
al.add(15);
al.add(0);

System.out.println(Collections.binarySearch(al, 10, new MyComparator())); //2


System.out.println(Collections.binarySearch(al, 13, new MyComparator())); //-3
System.out.println(Collections.binarySearch(al, 17)); //-6
}
}
classMyComparator implements Comparator {
publicint compare(Object obj1, Object obj2) {
Integer I1 = (Integer)obj1;
Integer I2 = (Integer)obj2;
return I2.compareTo(I1);
}
}

Note: For the List of n Elements


1) Successful Result Range: 0 To n-1
2) Unsuccessful Result Range: -(n+1) To -1
3) Total Result Range: -(n+1) To n-1
Search: -4 To -1 3) Total Result
Eg: For the List of 3 Elements Range: -4 To 2
1) Range of Successful Search: 0 -1 -2 -3A B Z 0 1 2
To 2 2) Range of Unsuccessful

☀ Reversing the Elements of List:public static void reverse(List l);

53 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Program: To Reverse Elements of List

importjava.util.*;
classCollectionsReverseDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add(15);
al.add(0);
al.add(20);
al.add(10);
al.add(5);
System.out.println(al); //[15, 0, 20, 10, 5]
Collections.sort(al);
System.out.println(al); //[0, 5, 10, 15, 20]
}
}

reverse() VsreverseOrder():
∙ We can Use reverse() to Reverse Order of Elements of List.
∙ We can Use reverseOrder() to get Reversed Comparator.

Comparator c1 = Collecctions.reverseOrder(Comparator c);


Eg:

Descending Order Ascending Order

Arrays
Arrays Class is an Utility Class to Define Several Utility Methods for Array
Objects.

☀ Sorting Elements of Array:

1) public static void sort(primitive[] p); To Sort According to Natural Sorting Order.

2) public static void sort(Object[] o); To Sort According to Natural Sorting Order.
54 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038, 
040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

3) public static void sort(Object[] o, Comparator c);To Sort According to Customized Sorting
Order.

Note:
∙ For Object Type Arrays we can Sort According to Natural Sorting Order OR
Customized Sorting Order.
∙ But we can Sort primitive[] Only Based on Natural Sorting.

Program: To Sort Elements of Array


importjava.util.*;
Arrays.sort(a);
classArraysSortDemo {
System.out.println("Primitive Array After
public static void main(String args[]) {
Sorting:"); for (int a1 : a) {
System.out.println(a1);
int[] a = {10, 5, 20, 11, 6};
}
System.out.println("Primitive Array Before
Sorting:"); for (int a1 : a) {
String[] s = {"A", "Z", "B"};
System.out.println(a1);
System.out.println("Object Array Before
}
Sorting:"); for (String s1 : s) {
System.out.println(s1); 10
} 11
20
Arrays.sort(s);
System.out.println("Object Array After Sorting:"); Object Array Before Sorting: A
for (String s1 : s) { Z
Primitive Array Before Sorting: 10 B
5
20 Object Array After Sorting: A
11 B
6 Z

Primitive Array After Sorting: 5 Object Array After Sorting By Comparator:


6
55 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
Z
System.out.println(s1);
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
} B
JAVA Means DURGA SIR

☀ Searching the Elements of Array:

1) public static intbinarySearch(primitive[] p, primitive target);


If the Primitive Array Sorted According to Natural Sorting Order then we have to Use this
Method.

2) public static intbinarySearch(Object[] a, Object target);


If the Object Array Sorted According to Natural Sorting Order then we have to Use this
Method.

3) public static intbinarySearch(Object[] a, Object target, Comparator c); If the Object


Array Sorted According to Comparator then we have to Use this Method.

Note: All Rules of Array Class binarySearch() are Exactly Same as Collections Class
binarySearch().

Program: To Search Elements of Array


importjava.util.Arrays;
importjava.util.Comparator;
import static java.util.Arrays.*;

classArraysSearchDemo {
public static void main(String args[]) {

int[] a = {10, 5, 20, 11, 6};


Arrays.sort(a); //Sort By Natural Order
System.out.println(Arrays.binarySearch(a, 6)); //1
System.out.println(Arrays.binarySearch(a, 14)); //-5

String[] s = {"A", "Z", "B"};


Arrays.sort(s);
System.out.println(binarySearch(s, "Z")); //2
System.out.println(binarySearch(s, "S")); //-3

Arrays.sort(s, new MyComparator());


System.out.println(binarySearch(s, "Z", new MyComparator())); //0
System.out.println(binarySearch(s, "S", new MyComparator())); //-2
System.out.println(binarySearch(s, "N")); //-4
}
}

classMyComparator implements Comparator {


publicint compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}

56 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Conversion of Array to List:

∙ Arrays Class contains asList() for this public static List asList(Object[] a); ∙ Strictly
Speaking this Method won't Create an Independent List Object, Just we are
Viewingexisting Array in List Form.

String[] s
AZB
List l

∙ By using Array Reference if we Perform any Change Automatically that Change will be
reflected to List Reference.
∙ Similarly by using List Reference if we Perform any Change Automatically that Change will
be reflected to Array.
∙ By using List Reference if we aretrying to Perform any Operation which Varies the Size
then we will get Runtime Exception Saying UnsuportedOperationException.

l.add("K");//RE: UnsuportedOperationException
Eg: UnsuportedOperationExcept
l.remove(1);//RE: ion l.set(1, "K"); √

∙ By using List Reference if we are trying to Replace with Heterogeneous Objects then we will
get Runtime Exception Saying ArrayStoreException.

Program: To View Array in List Form

importjava.util.*;
classArraysAsListDemo {
public static void main(String args[]) {

String[] s = {"A", "Z", "B"};


List l = Arrays.asList(s);
System.out.println(l); //[A, Z, B]
s[0] = "K";
System.out.println(l); //[K, Z, B]

l.set(1, "L");

for (String s1 : s )
System.out.println(s1); //K L B

l.add("Durga"); //RE: java.lang.UnsupportedOperationException


l.remove(2); //RE: java.lang.UnsupportedOperationException
l.set(1, new Integer[10]); //RE:
java.lang.ArrayStoreException:[Ljava.lang.Integer; }
}

57 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Concurrent Collections (1.5)

Need fo Concurrent Collections


The Important Concurrent Classes
ConcurrentHashMap
CopyOnWriteArrayList
CopyOnWriteArraySet
ConcurrentMap (I)
ConcurrentHashMap
Difference between HashMap and ConcurrentHashMap Difference
between ConcurrentHashMap, synchronizedMap() and Hashtable
CopyOnWriteArrayList (C)
Differences between ArrayList and CopyOnWriteArrayList
Differences between CopyOnWriteArrayList, synchronizedList() and vector()
CopyOnWriteArraySet
Differences between CopyOnWriteArraySet() and synchronizedSet()
Fail Fast Vs Fail Safe Iterators
Differences between Fail Fast and Fail Safe Iterators
Enum with Collections
EnumSet
EnumMap
Queue
PriorityQueue
BlockingQueue
TransferQueue
Deque
BlockingDeque (I)
58 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Need fo Concurrent Collections

∙ Tradition Collection Object (Like ArrayList, HashMapEtc) can be accessed by Multiple


Threads simultaneously and there May be a Chance of Data Inconsistency Problems and
Hence these are Not Thread Safe.
∙ Already existing Thread Safe Collections (Vector, Hashtable, synchronizedList(),
synchronizedSet(), synchronizedMap() ) Performance wise Not Upto the Mark. ∙ Because for
Every Operation Even for Read Operation Also Total Collection will be loaded by Only One
Thread at a Time and it Increases waiting Time of Threads.

importjava.util.ArrayList;
importjava.util.Iterator;
class Test {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("A");
al.add("B");
al.add("C");
Iterator itr = al.iterator();
while (itr.hasNext()){
A
String s = (String)itr.next();
B
System.out.println(s);
C
//al.add("D");
} A
} RE:
} java.util.ConcurrentModificationException
∙ Another Big Problem with Traditional Collections is while One Thread iterating Collection,
the Other Threads are Not allowed to Modify Collection Object simultaneously if we are
trying to Modify then we will get ConcurrentModificationException.
∙ Hence these Traditional Collection Objects are Not Suitable for Scalable Multi Threaded
Applications.
∙ To Overcome these Problems SUN People introduced Concurrent Collections in 1.5 Version.

1) Concurrent Collections are Always Thread Safe.


2) When compared with Traditional Thread Safe Collections Performance is More because of
different Locking Mechanism.
3) While One Thread interacting Collection the Other Threads are allowed to Modify
Collection in Safe Manner.

Hence Concurrent Collections Never threw

ConcurrentModificationException. The Important Concurrent Classes are

❖ ConcurrentHashMap
❖ CopyOnWriteArrayList
❖ CopyOnWriteArraySet

59 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
Concurr

Concurr
entHash

entMap
Map (C)
ConcurrentMap (I):
(I)
Map (I) JAVA Means DURGA SIR

Methods: It Defines the following 3 Specific Methods.

1) Object putIfAbsent(Object Key, Object Value)


To Add Entry to the Map if the specified Key is Not Already Available.

Object putIfAbsent(Object key, Object value)


if (!map.containsKey(key)) {
map.put(key, value);
}
else {
returnmap.get(key);
}

put()
If the Key is Already Available, Old Value will If the Key is Already Present then Entry won’t
be replaced with New Value and Returns Old be added and Returns Old associated Value. If
Value. the Key is Not Available then Only Entry will
be added.
putIfAbsent()

importjava.util.concurrent.ConcurrentHashMap;
class Test {
public static void main(String[] args) {
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(101, "Durga");
m.put(101, "Ravi");
System.out.println(m); //{101=Ravi}
m.putIfAbsent(101, "Siva");
System.out.println(m); //{101=Ravi}
}
}

60 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

2) boolean remove(Object key, Object value)


Removes the Entry if the Key associated with specified Value Only.

if ( map.containsKey (key) &&map.get(key).equals(value) ) {


map.remove(key);
return true;
}
else {
return false;
}

importjava.util.concurrent.ConcurrentHashMap;
class Test {
public static void main(String[] args) {
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(101, "Durga");
m.remove(101, "Ravi"); //Value Not Matched with Key So Nor Removed
System.out.println(m); //{101=Durga}
m.remove(101, "Durga");
System.out.println(m); //{}
}
}

61 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

3) boolean replace(Object key, Object oldValue, Object newValue)

If the Key Value


Matched then
Replace with

if ( map.containsKey (key) &&map.get(key).equals(oldvalue) ) {


map.put(key, newValue);
return true;
}
else {
return false;
}
importjava.util.concurrent.ConcurrentHashMap;
class Test {
public static void main(String[] args) {
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(101, "Durga");
m.replace(101, "Ravi", "Siva");
System.out.println(m); //{101=Durga}
m.replace(101, "Durga", "Ravi");
System.out.println(m); //{101=Ravi}
}
}

ConcurrentHashMap
∙ Underlying Data Structure is Hashtable.
∙ ConcurrentHashMap allows Concurrent Read and Thread Safe Update Operations. ∙ To
Perform Read Operation Thread won’t require any Lock. But to Perform Update Operation
Thread requires Lock but it is the Lock of Only a Particular Part of Map (Bucket Level Lock).

62 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ Instead of Whole Map Concurrent Update achieved by Internally dividing Map into
Smaller Portion which is defined by Concurrency Level.
∙ The Default Concurrency Level is 16.
∙ That is ConcurrentHashMap Allows simultaneous Read Operation and simultaneously 16
Write (Update) Operations.
∙ null is Not Allowed for Both Keys and Values.
∙ While One Thread iterating the Other Thread can Perform Update Operation and
ConcurrentHashMap Never throw ConcurrentModificationException.

Constructors:

1) ConcurrentHashMap m = new ConcurrentHashMap();


Creates an Empty ConcurrentHashMap with Default Initial Capacity 16 and Default Fill
Ratio
0.75and Default Concurrency Level 16.

2) ConcurrentHashMap m = new ConcurrentHashMap(intinitialCapacity);


3) ConcurrentHashMap m = new ConcurrentHashMap(intinitialCapacity, float fillRatio);
4) ConcurrentHashMap m = new ConcurrentHashMap(intinitialCapacity, float fillRatio,
intconcurrencyLevel);
5) ConcurrentHashMap m = new ConcurrentHashMap(Map m);
importjava.util.concurrent.ConcurrentHashMap;
class Test {
public static void main(String[] args) {
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(101, "A");
m.put(102, "B");
m.putIfAbsent(103, "C");
m.putIfAbsent(101, "D");
m.remove(101, "D");
m.replace(102, "B", "E");
System.out.println(m); //{103=C, 102=E, 101=A}
}
}

63 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

importjava.util.concurrent.ConcurrentHashMap;
importjava.util.*;
classMyThread extends Thread {
//static HashMap m = new HashMap(); // java.util.ConcurrentModificationException
staticConcurrentHashMap m = new ConcurrentHashMap();
public void run() {
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {}
System.out.println("Child Thread updating Map");
m.put(103, "C");
}
public static void main(String[] args) throws InterruptedException {
m.put(101, "A");
m.put(102, "B");
MyThread t = new MyThread();
t.start();
Set s = m.keySet();
Iterator itr = s.iterator();
while (itr.hasNext()) {
Integer I1 = (Integer) itr.next();
SOP("Main Thread iterating and Current Entry
is:"+I1+"..............."+m.get(I1)); Thread.sleep(3000);
} Main Thread iterating and Current Entry
System.out.println(m); is:102...............B Child Thread updating Map
} Main Thread iterating and Current Entry
} is:101...............A {103=C, 102=B, 101=A}
∙ In the Above Example while Main Thread iterating Map Object Child Thread is allowed to
Update and we won’t get any ConcurrentModificationException.
∙ If we Replace ConcurrentHashMap with HashMap then we will get
ConcurrentModificationException.

importjava.util.Iterator;
class Test {
public static void main(String[] args) throws InterruptedException {
ConcurrentHashMap m = new ConcurrentHashMap();
m.put(101, "A");
m.put(102, "B");
Iterator itr = m.keySet().iterator();
m.put(103, "C");
while (itr.hasNext()) {
Integer I1 = (Integer) itr.next();
System.out.println(I1+"............."+m.get(I1));
Thread.sleep(3000);
}
System.out.println(m); 101.............A
} {103=C, 102=B, 101=A}
}
102.............B
64 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Reason:
∙ In the Case of ConcurrentHashMap iterator creates a Read Only Copy of Map Object and
iterates over that Copy if any Changes to the Map after getting iterator it won’t be affected/
reflected.
∙ In the Above Program if we Replace ConcurrentHashMap with HashMap then we will get
ConcurrentModificationException.

Difference between HashMap and ConcurrentHashMap


HashMap ConcurrentHashMap

It is Not Thread Safe. It is Thread Safe.

Relatively Performance is High because Relatively Performance is Low because


Threads are Not required to wait to Some Times Threads are required to wait to
Operate on HashMap. Operate on ConcurrentHashMap.
While One Thread iterating HashMap the While One Thread iterating
Other Threads are Not allowed to Modify ConcurrentHashMap the Other Threads
Map Objects Otherwise we will get Runtime are allowed to Modify Map Objects in
Exception Saying Safe Manner and it won’t throw
ConcurrentModificationException. ConcurrentModificationException.

Iterator of HashMap is Fail-Fast and it Iterator of ConcurrentHashMap is


throws ConcurrentModificationException. Fail-Safe and it won’t
throwsConcurrentModificationException.

null is allowed for Both Keys and Values. null is Not allowed for Both Keys and
Values. Otherwise we will get
NullPointerException.

Introduced in 1.2 Version. Introduced in 1.5 Version.

65 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Difference between ConcurrentHashMap, synchronizedMap() and


Hashtable
Hashtable
ConcurrentHashMap synchronized

We will get Thread Safety We will get Th


without locking Total Map by locking W We will get Thread Safety
Object Just with Bucket Object. by locking Whole Map
Level Lock. Object.

Read Operation can be


At a Time Multiple performed without Lock
Threads are allowed to but write Operation can
Operate on Map Object be
in Safe Manner. performed with Bucket
Level Lock.
Every Read and Write
Operations require Total
At a Time Only One Thread Map Object Lock. Every Read and Write
is allowed to Perform any Operations require Total
Operation on Map Object. Map Object Lock.

At a Time Only One Thread


is allowed to Operate on
Map Object.

While One Thread W


While One Thread iterating Map Object, ite
iterating Map Object, the the Other Ot
Other Threads are Not allowed Th
Threads are allowed to to Modify Map. to
Modify Map and we won’t Otherwise we will get Ot
get ConcurrentModificationE Co
ConcurrentModificationEx xce ption ce
ce ption.

Iterator of synchronizedMap
Iterator of Iterator of
is Fail-Fast and it will raise
ConcurrentHashMap is synchronizedMap is
ConcurrentModificationExc
Fail Safe and won’t raise Fail-Fast and it will raise
e ption.
ConcurrentModificationE ConcurrentModificationEx
xce ption. ce ption.

null is Not allowed for null is allowed for Both null is Not allowed for
Both Keys and Values. Keys and Values. Both Keys and Values.

Introduced in 1.5 Version. Introduced in 1.2 Version. Introduced in 1.0 Version.

CopyOnWriteArrayList (C):

Collection (I)

List (I)
66 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ It is a Thread Safe Version of ArrayList as the Name indicates CopyOnWriteArrayList


Creates a Cloned Copy of Underlying ArrayList for Every Update Operation at Certain
Point Both will Synchronized Automatically Which is taken Care by JVM Internally.
∙ As Update Operation will be performed on cloned Copy there is No Effect for the Threads
which performs Read Operation.
∙ It is Costly to Use because for every Update Operation a cloned Copy will be Created.
Hence CopyOnWriteArrayList is the Best Choice if Several Read Operations and Less
Number of Write Operations are required to Perform.
∙ Insertion Order is Preserved.
∙ Duplicate Objects are allowed.
∙ Heterogeneous Objects are allowed.
∙ null Insertion is Possible.
∙ It implements Serializable, Clonable and RandomAccess Interfaces.
∙ While One Thread iterating CopyOnWriteArrayList, the Other Threads are allowed to
Modify and we won’t get ConcurrentModificationException. That is iterator is Fail Safe. ∙
Iterator of ArrayList can Perform Remove Operation but Iterator of
CopyOnWriteArrayList can’t Perform Remove Operation. Otherwise we will get
RuntimeException Saying UnsupportedOperationException.

Constructors:

1) CopyOnWriteArrayList l = new CopyOnWriteArrayList();


2) CopyOnWriteArrayList l = new CopyOnWriteArrayList(Collection c);
3) CopyOnWriteArrayList l = new CopyOnWriteArrayList(Object[] a);

Methods:

1. booleanaddIfAbsent(Object o): The Element will be Added if and Only if List doesn’t
contain this Element.

CopyOnWriteArrayList l = new CopyOnWriteArrayList();


l.add("A");
l.add("A");
l.addIfAbsent("B");
l.addIfAbsent("B");
System.out.println(l); //[A, A, B]

67 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

2. ntaddAllAbsent(Collection c): The Elements of Collection will be Added to the List if


Elements are Absent and Returns Number of Elements Added.

ArrayList l = new ArrayList();


l.add("A");
l.add("B");

CopyOnWriteArrayList l1 = new CopyOnWriteArrayList();


l1.add("A");
l1.add("C");
System.out.println(l1); //[A, C]
l1.addAll(l);
System.out.println(l1); //[A, C, A, B]

ArrayList l2 = new ArrayList();


l2.add("A");
l2.add("D");
l1.addAllAbsent(l2);
System.out.println(l1); //[A, C, A, B, D]

importjava.util.concurrent.CopyOnWriteArrayList;
importjava.util.ArrayList;
class Test {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add("A");
l.add("B");

CopyOnWriteArrayList l1 = new CopyOnWriteArrayList();


l1.addIfAbsent("A");
l1.addIfAbsent("C");
l1.addAll(l);

ArrayList l2 = new ArrayList();


l2.add("A");
l2.add("E");
l1.addAllAbsent(l2);

System.out.println(l1); //[A, C, A, B, E]
}
}

importjava.util.concurrent.CopyOnWriteArrayList;
importjava.util.*;
classMyThread extends Thread {
staticCopyOnWriteArrayList l = new CopyOnWriteArrayList();
68 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
public void run() {
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
try { Thread.sleep(2000); }
catch (InterruptedException e) {}
System.out.println("Child Thread Updating List");
l.add("C");
JAVA Means DURGA SIR

∙ In the Above Example while Main Thread iterating List Child Thread is allowed to Modify
and we won’t get any ConcurrentModificationException.
∙ If we Replace CopyOnWriteArrayList with ArrayList then we will get
ConcurrentModificationException.
∙ Iterator of CopyOnWriteArrayList can’t Perform Remove Operation. Otherwise we will get
RuntimeException: UnsupportedOperationException.

importjava.util.concurrent.CopyOnWriteArrayList;
importjava.util.Iterator;
class Test {
public static void main(String[] args){
CopyOnWriteArrayList l = new CopyOnWriteArrayList();
l.add("A");
l.add("B");
l.add("C");
l.add("D");
System.out.println(l); //[A, B, C, D]
Iterator itr = l.iterator();
while (itr.hasNext()) {
String s = (String)itr.next();
if (s.equals("D"))
itr.remove();
}
System.out.println(l); //RE: java.lang.UnsupportedOperationException
}
}

∙ If we Replace CopyOnWriteArrayList with ArrayList we won’t get any


UnsupportedOperationException.
∙ In this Case the Output is
▪ [A, B, C, D]
▪ [A, B, C]

importjava.util.concurrent.CopyOnWriteArrayList;
importjava.util.Iterator;
class Test {
public static void main(String[] args) {
CopyOnWriteArrayList l = new CopyOnWriteArrayList();
l.add("A");
l.add("B");
l.add("C");
Iterator itr = l.iterator();
l.add("D");
while (itr.hasNext()) {
String s = (String)itr.next();
System.out.println(s);
} ABC
}
}
69 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Reason:
∙ Every Update Operation will be performed on Separate Copy Hence After getting iterator if
we are trying to Perform any Modification to the List it won’t be reflected to the iterator.

∙ In the Above Program if we ReplaceCopyOnWriteArrayList with ArrayList then we will


get RuntimeException: java.util.ConcurrentModificationException.

Differences between ArrayList and CopyOnWriteArrayList

ArrayList CopyOnWriteArrayList

It is Not Thread Safe.


While One Thread iterating List Object,
the Other Threads are allowed to Modify
List in Safe Manner and we won’t get
While One Thread iterating List Object, the
ConcurrentModificationException.
Other Threads are Not allowed to Modify List
Otherwise we will get Iterator is Fail-Safe.
ConcurrentModificationException
. Iterator is Fail-Fsat. Iterator of CopyOnWriteArrayList can’t
Iterator of ArrayList can Perform Remove Perform Remove Operation Otherwise we
Operation. will get RuntimeException:
UnsupportedOperationException.

Introduced in 1.5 Version.


Introduced in 1.2 Version.
It is Not Thread Safe because Every
Update Operation will be performed on
Separate cloned Coy.
70 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Differences between CopyOnWriteArrayList, synchronizedList() and


vector()

CopyOnWriteArrayList synchronizedList() vector()


We will get Thread Safety Iterator canPerform
because Every Update Remove Operation.
Operation will be performed
We will get Thread Safety
on Separate cloned Copy.
because at a Time List can
At a Time Multiple be accessed by Only One
Threads are allowed to Thread at a Time.
Access/
We will get Thread Safety
Operate on
because at a Time Only One
CopyOnWriteArrayList.
Thread is allowed to Access
At a Time Only One Thread Vector Object.
is allowed to Perform any
At a Time Only One Thread
Operation on List Object.
While One Thread is allowed to Operate on
iterating List Object, the Vector Object.
Other
Threads are allowed to While One Thread
Modify Map and we won’t
iterating , the Other
get While One Thread
Threads are Not allowed
ConcurrentModificationEx iterating, the Other
to Modify List.
ce ption. Threads are Not allowed
Otherwise we will get
to Modify Vector.
ConcurrentModificationE
Otherwise we will get
xce ption
ConcurrentModificationE
Iterator is Fail-Safe and xce ption
won’t raise
ConcurrentModificationE Iterator is Fail-Fast and it
xce ption.
will raise Iterator is Fail-Fast and it will
ConcurrentModificationE raise
xce ption. ConcurrentModificationExc
e ption.
Iterator can’t Perform
Iterator can Perform Remove
Remove Operation
Operation.
Otherwise we will get
UnsupportedOperationExc
ept ion.

Introduced in 1.5 Version. Introduced in 1.2 Version. Introduced in 1.0 Version.

CopyOnWriteArraySet :

Collection (I)

Set (I)
CopyOnWriteArraySet (C)

∙ It is a Thread Safe Version of Set.


∙ Internally Implement by CopyOnWriteArrayList.
∙ Insertion Order is Preserved.
∙ Duplicate Objects are Notallowed.
∙ Multiple Threads can Able to Perform Read Operation simultaneously but for Every
Update Operation a Separate cloned Copy will be Created.
∙ As for Every Update Operation a Separate cloned Copy will be Created which is Costly
Hence if Multiple Update Operation are required then it is Not recommended to Use
CopyOnWriteArraySet.

71 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ While One Thread iterating Set the Other Threads are allowed to Modify Set and we won’t
get ConcurrentModificationException.
∙ Iterator of CopyOnWriteArraySet can PerformOnly Read Operation and won’t Perform
Remove Operation. Otherwise we will get RuntimeException:
UnsupportedOperatonException.

Constructors:

1) CopyOnWriteArraySets = new CopyOnWriteArraySet();


Creates an Empty CopyOnWriteArraySet Object.

2) CopyOnWriteArraySet s = new CopyOnWriteArraySet(Collection c);


Creates CopyOnWriteArraySet Object which is Equivalent to given Collection Object.

Methods:Whatever Methods Present in Collection and Set Interfaces are the Only Methods
Applicable for CopyOnWriteArraySet and there are No Special Methods.
importjava.util.concurrent.CopyOnWriteArraySet;
class Test {
public static void main(String[] args) {
CopyOnWriteArraySet s = new CopyOnWriteArraySet();
s.add("A");
s.add("B");
s.add("C");
s.add("A");
s.add(null);
s.add(10);
s.add("D");
Differences between CopyOnWriteArraySet() and synchronizedSet()
CopyOnWriteArraySet() synchronizedSet()
It is Thread Safe because Every It is Thread Safe because at a Time Only
Update Operation will be performed One Thread can Perform Operation.
on Separate Cloned Copy.

While One Thread iterating Set, the Other While One Thread iterating, the
Threads are allowed to Modify and we Other Threads are Not allowed to
won’t get Modify Seta Otherwise we will get
ConcurrentModificationException. ConcurrentModificationException.

Iterator is Fail Safe. Iterator is Fail Fast.

72 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

Iterator can Perform Both Read and Remove


Iterator can Perform Only Read Operation Operations.
and can’t Perform Remove Operation
Introduced in 1.7 Version.
Otherwise we will get RuntimeException
Saying UnsupportedOperationException.
Introduced in 1.5 Version.
Fail Fast Iterator
Fail Fast Vs Fail Safe Iterators:
JAVA Means DURGA SIR

Fail Fast Iterator:While One Thread iterating Collection if Other Thread trying to Perform
any Structural Modification to the underlying Collection then immediately Iterator Fails by
raising ConcurrentModificationExcepion. Such Type of Iterators are Called Fail Fast
Iterators.

importjava.util.ArrayList;
importjava.util.Iterator;
class Test {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add("A");
l.add("B"); while(itr.hasNext()) {
Iterator itr = l.iterator(); Fail Fast Iterator

String s = (String)itr.next();
System.out.println(s); //A
l.add("C"); // java.util.ConcurrentModificationException
}
}
}
Note: Internally Fail Fast Iterator will Use Some Flag named with MOD to Check underlying
Collection is Modified OR Not while iterating.

Fail Safe Iterator:

∙ While One Thread iterating if the Other Threads are allowed to Perform any Structural
Changes to the underlying Collection, Such Type of Iterators are Called Fail Safe Iterators. ∙
Fail Safe Iterators won’t raise ConcurrentModificationException because Every Update
Operation will be performed on Separate cloned Copy.

importjava.util.concurrent.CopyOnWriteArraySet;
importjava.util.Iterator;
class Test {
public static void main(String[] args) {
CopyOnWriteArraySet l = new CopyOnWriteArraySet();
l.add("A");
l.add("B"); String s = (String)itr.next();
Iterator itr = l.iterator(); Fail Safe Iterator
while(itr.hasNext()) {

73 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
System.out.println(s); //A
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
l.add("C");
}
}

}A
JAVA Means DURGA SIR

Differences between Fail Fast and Fail Safe Iterators:


Property Fail Fast Fail Safe
Does it through
Yes No
ConcurrentModificationException?
Is the Cloned Copy will be Created? No Yes Memory Problems No Yes
Examples ArrayList, Vector,
ConcurrentHashMap,
HashMap, HashSet
CopyOnWriteArrayList,
CopyOnWriteArraySet
74 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Enum with Collections

Collection (I)

Set (I)

EnumSet (AC)
(1.5 V)

RegularEnumSetJumboEnumSet

EnumSet:

∙ Ii is a specially designed Set implemented Collection Applicable Only for Enum. ∙


Introduced in 1.5 Version.
∙ EnumSet is Internally implemented as Bit Vectors which Improves Performance Internally. ∙
The Performance of EnumSet is Very High if we want to Store Enum Constants than
Traditional Collections (Like HashSet, LinkedHashSetEtc).
∙ All Elements of the EnumSet should be from Same Enum Type Only if we are trying to Add
Elements from different enums then we will get Compile Time Error (i.e. EnumSet is Type
Safe Collection).
∙ Iterator Returned by EnumSet Traverse, Iterate Elements in their Natural Order i.e. the
Order in which the Enum Constants are declared i.e. the Order Returned by ordinal(). ∙
Enum Iterator Never throwConcurrentModificationException.
∙ Inside EnumSet we can’t Add null Otherwise we will get NullPointerException. ∙ EnumSet is
an Abstract Class and Hence we can’t Create Object directly by using new Key Word.
∙ EnumSet defined Several Factory Methods to Create EnumSet Object. ∙
EnumSet defines 2 Child Classes.
▪ RegularEnumSet
▪ JumboEnumSet
∙ The Factory Methods will Return this Class Objects Internally Based on Size if the Size is < 64
then RegularEnumSet will be choosed Otherwise if Size > 64 then JumboEnumSet will be
choosed.

EnumMap:

∙ Ii is a specially designed Map to Use Enum Type Objects as Keys.


∙ Introduced in 1.5 Version.
∙ It implements Serializable and Cloneable Interfaces.
∙ EnumMap is Internally implemented by using Bit Vectors (Arrays), which Improves
Performance when compared with Traditional Map Object Like HashMap Etc. ∙ All
Keys to the EnumMap should be from a Single Enum if we are trying to Use from
different Enum then we will get Compile Time Error. Hence EnumMap is Type Safe. ∙
Iterator Never throwConcurrentModificationException.

75 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ Iterators of EnumMap iterate Elements according to Ordinal Value of Enum Keys i.e. in
which Order Enum Constants are declared in the Same Order Only Iterator will be
iterated.
∙ null Key is Not allowed Otherwise we will get NullPointerException.

Constructors
1) EnumMap m = new EnumMap(Class KeyType)
Creates an Empty EnumMap with specified Key Type.

2) EnumMap m = new EnumMap(EnumMap m1)


Creates an EnumMap with the Same Key Type and the specified
EnumMap.Internally containing Same Mappings.

3) EnumMap m = new EnumMap(Map m1)


To Create and Equivalent EnumMap for given Map.

Methods:
EnumMap doesn’t contain any New Methods. We have to Use General Map Methods Only.

importjava.util.*;
enum Priority {
LOW, MEDIUM, HIGH
}
classEnumMapDemo {
public static void main(String[] args) {
EnumMap<Priority, String> m = new EnumMap<Priority, String> (Priority.class);
m.put(Priority.LOW, "24 Hours Response Time");
m.put(Priority.MEDIUM, "3 Hours Response Time");
m.put(Priority.HIGH, "1 Hour Response Time");
System.out.println(m);
Set s = m.keySet();
Queue
Iterator<Priority>itr = s.iterator();
while(itr.hasNext()) {
Priority p = itr.next();
System.out.println(p+"........."+m.get(p));
}
}
}
{LOW=24 Hours Response Time, MEDIUM=3 Hours Response Time, HIGH=1 Hour Response
Time} LOW.........24 Hours Response Time
MEDIUM.........3 Hours Response Time
HIGH.........1 Hour Response Time

76 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Overview of java Queues

Collection (I)
(1.2 V)

Queue (I)
(1.5 V)

PriorityQueueBlockingQueueTransferQueue
(1.5 V) (1.5 V) (1.7 V)

Queue:

If we want to Represent a Group of Individual Objects Prior to processing then Use should go
for Queue.
∙ Queue is Child Interface of Collection.

PriorityQueue:

∙ It is the Implementation Class of Queue.


∙ If we want to Represent a Group of Individual Objects Prior to processing according to
Priority then we should go for PriorityQueue.

BlockingQueue:

∙ It is the Child Interface of Queue. Present in java.util.Concurrent Package. ∙


It is a Thread Safe Collection.
∙ It is a specially designed Collection Not Only to Store Elements but also Supports Flow
Control by Blocking Mechanism.
∙ If Queue is Empty take() (Retrieval Operation) will be Blocked until Queue will be Updated
with Items.
∙ put() will be blocked if Queue is Full until Space Availability.
∙ This Property Makes BlockingQueue Best Choice for Producer Consumer Problem. When
One Thread producing Items to the Queue and the Other Thread consuming Items from the
Queue.

77 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Collection (I)
(1.2 V)

Queue (I)
(1.5 V)

BlockingDeque(I)
(1.7 V)

ArrayBlockingQueue
PriorityBlockingQueue
LinkedBlockingQueue
synchronousQueue

TransferQueue:

∙ In BlockingQueue we can Only Put Elements into the Queue and if Queue is Full then Our
put() will be blocked until Space is Available.
∙ But in TransferQueue we can also Block until Other Thread receiving Our Element. Hence
this is the Behavior of transfer().
∙ In BlockingQueue we are Not required to wait until Other Threads Receive Our Element but
in TransferQueue we have to wait until Some Other Thread Receive Our Element. ∙
TrasferQueue is the Best Choice for Message Passing Application where Guarantee for the
Delivery.

Collection (I)
(1.2 V)
Queue (I)
Deque (I) (1.5 V)
Collection (I) LinkedTransferQueue
(1.2 V) (1.7 V)
BlockingQueueTransferQueue
(1.5 V) (1.7 V) Queue (I) Deque(I)
(1.5 V) (1.7 V)

78 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

∙ It Represents a Queue where we can Insert and Remove Elements from Deque, Both Ends
of Queue i.e. Deque Means Double Ended Queue.
∙ It is Also pronounced as Deck Like Deck of Cards.

Collection (I)
(1.2 V)

Queue (I)
(1.5 V)

Deque(I)
(1.7 V)

ArrayDeque
ConcurrentLinkedDeque
LinkedList

BlockingDeque (I) 1.6 V

∙ It is the Child Interface of BlockingQueue and Deque.


∙ It is a Simple Deque with Blocking Operations but wait for the Deque to become Non Empty
fro Retrieval Operation and wait for Space to Store Element.

Collection (I)
(1.2 V)

Queue (I)
(1.5 V)

BlockingQueue (I) Deque (I)


(1.5 V) (1.6 V)

BlockingDeque (I)
(1.6 V)

LinkedBlockingDeque (I)
(1.6 V)

79 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com
JAVA Means DURGA SIR

Collection (I)

Queue (I)
(1.5 V)

PriorityQueueBlockingQueue (I) Deque (I)


(1.5 V) (1.5 V) (1.6 V)

TransferQueue (I) ArrayBlockingQueueBlockingDeque (I) PriorityBlockingQueue (1.6 V)


LinkedBlockingQueue
synchronousQueue
LinkedTransferQueueLinkedBlockingDeque (I)
(1.7 V) (1.6 V)
80 DURGASOFT, # 202,2 nd
Floor,HUDA Maitrivanam,Ameerpet, Hyderabad - 500038,
 040 – 64 51 27 86, 80 96 96 96 96, 9246212143 | www.durgasoft.com

You might also like