14 Collections Frame Work
14 Collections Frame Work
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
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
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
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.
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:
With Respect to Memory Arrays are With Respect to Memory Collections are
Not Recommended to Use. 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.
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)
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.
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
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)
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
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)
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:
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)
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()
2) List:
5) Object set(int index, Object new):To Replace the Element Present at specified Index
with provided Object and Returns Old Object.
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
∙ 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
importjava.util.ArrayList;
classArrayListDemo {
public static void main(String[] args){
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.
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.
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.
Similarly we can get Synchronized Version of Set and Map Objects by using the following
Methods of Collection Class.
∙ 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:
Constructors:
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:
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
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
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:
Methods:
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
∙ 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();
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.
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:
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.
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:
Methods:
∙ ListIteratoris the Child Interface of Iterator and Hence All Iterator Methods by Default
Available to the ListIterator.
Iterator (I)
ListIterator (I)
publicbooleanhasPrevious
() public Object previous()
publicintpreviousIndex() Direction
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]
Note: The Most Powerful Cursor is ListIterator. But its Limitation is, it is Applicable Only for
List Objects.
Property
En
Single Direction
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()
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:
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
Constructors:
1) HashSet h = new HashSet();
Creates an Empty HashSet Object with Default Initial Capacity 16 and Default Fill Ratio :
0.75.
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.
3.2) SortedSet:
Methods:
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
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:
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
Creates an Empty TreeSet Object where all Elements will be Inserted According to Default
Natural Sorting Order.
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));
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);
}
}
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:
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.
“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.
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):
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].
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.
∙ 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
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,
Defines Only One Method compareTo(). Defines 2 Methods compare() and equals().
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)
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
2) void putAll(Map m)
5) booleancontainsKey(Object key)
6) booleancontainsValue(Object value)
7) booleanisEmpty()
8) int size()
9) void clear()
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:
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.
null is allowed for Both Keys and Values. null is Not allowed for Both Keys
and Values. Otherwise we will get
NPE.
By Default HashMap is Non- Synchronized. But we can get Synchronized Version of HashMap
by using synchronizedMap() of Collections Class.
Constructors:
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);
}
}
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:
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:
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
WeakHashMap:
}{temp=Durga}
{temp=Durga}
{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
∙ 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:
∙ 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:
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"
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:
Constructors:
1) Hashtable h = new Hashtable();
Creates an Empty Hashtable Object with Default Initial Capacity 11 and
Default Fill Ratio 0.75.
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;
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.
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
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);
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}
}
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
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:
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
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)
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.
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));
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);
}
}
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.
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
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);
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
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.
Arrays
Arrays Class is an Utility Class to Define Several Utility Methods for Array
Objects.
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.
Note: All Rules of Array Class binarySearch() are Exactly Same as Collections Class
binarySearch().
classArraysSearchDemo {
public static void main(String args[]) {
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
∙ 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.
importjava.util.*;
classArraysAsListDemo {
public static void main(String args[]) {
l.set(1, "L");
for (String s1 : s )
System.out.println(s1); //K L B
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
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.
❖ 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
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
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
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:
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.
null is allowed for Both Keys and Values. null is Not allowed for Both Keys and
Values. Otherwise we will get
NullPointerException.
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
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.
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
Constructors:
Methods:
1. booleanaddIfAbsent(Object o): The Element will be Added if and Only if List doesn’t
contain this Element.
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
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");
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
}
}
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.
ArrayList CopyOnWriteArrayList
CopyOnWriteArraySet :
Collection (I)
Set (I)
CopyOnWriteArraySet (C)
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:
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.
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
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.
∙ 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
Collection (I)
Set (I)
EnumSet (AC)
(1.5 V)
RegularEnumSetJumboEnumSet
EnumSet:
EnumMap:
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.
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
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:
BlockingQueue:
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
Collection (I)
(1.2 V)
Queue (I)
(1.5 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)