Documente Academic
Documente Profesional
Documente Cultură
com
1 Collections
2 Agenda
3 1. Introduction
4 2. Limitations of Object[] array
5 3. Differences between Arrays and Collections ?
6 4. 9(Nine) key interfaces of collection framework
7 i. Collection
8 ii. List
9 iii. Set
10 iv. SortedSet
11 v. NavigableSet
12 vi. Queue
13 vii. Map
14 viii. SortedMap
15 ix. NavigableMap
16 5. What is the difference between Collection and
17 Collections ?
18 6. In collection framework the following are legacy
19 characters
20 7. Collection interface
21 8. List interface
22 9. ArrayList
23 o Differences between ArrayList and Vector ?
25 10. LinkedList
26 11. Vector
27 12. Stack
28 13. The 3 cursors of java
29 0. Enumeration
30 1. Iterator
1
Karrasankar158@gmail.com
1 2. ListIterator
2 o Compression of Enumeration , Iterator and
3 ListIterator ?
4 14. Set interface
5 15. HashSet
6 16. LinkedHashSet
7 17. Diff b/w HashSet & LinkedHashSet
8 18. SortedSet
9 19. TreeSet
10 o Null acceptance
21 28. LinkedHashMap
22 29. IdentityHashMap
23 30. WeakHashMap
24 31. SortedMap
25 32. TreeMap
26 33. Hashtable
27 34. Properties
28 35. 1.5v enhancements
29 o Queue interface
30 o PriorityQueue
2
Karrasankar158@gmail.com
1 o NavigableSet
2 o NavigableMap
3 37. Utility classes :
4 o Collections class
5 ▪ Sorting the elements of a List
7 ▪ Conclusions
8 o Arrays class
9 ▪ Sorting the elements of array
12 Introduction:
13 1. An array is an indexed collection of fixed no of
14 homogeneous data elements. (or)
15 2. An array represents a group of elements of same data
16 type.
17 3. The main advantage of array is we can represent huge
18 no of elements by using single variable. So that
19 readability of the code will be improved.
20 Limitations of Object[] array:
21 1. Arrays are fixed in size that is once we created an
22 array there is no chance of increasing (or) decreasing
23 the size based on our requirement hence to use arrays
24 concept compulsory we should know the size in
25 advance which may not possible always.
26 2. Arrays can hold only homogeneous data elements.
27 Example:
28 Student[] s=new Student[10000];
3
Karrasankar158@gmail.com
1 s[0]=new Student();//valid
2 s[1]=new Customer();//invalid(compile time error)
3 Compile time error:
4 Test.java:7: cannot find symbol
5 Symbol: class Customer
6 Location: class Test
7 s[1]=new Customer();
8 3) But we can resolve this problem by using object type
9 array(Object[]).
10 Example:
11 Object[] o=new Object[10000];
12 o[0]=new Student();
13 o[1]=new Customer();
14 4) Arrays concept is not implemented based on some data
15 structure hence ready-made methods support we can't
16 expert. For every requirement we have to write the code
17 explicitly.
18 To overcome the above limitations we should go for
19 collections concept.
20 1. Collections are growable in nature that is based on our
21 requirement we can increase (or) decrease the size
22 hence memory point of view collections concept is
23 recommended to use.
24 2. Collections can hold both homogeneous and
25 heterogeneous objects.
26 3. Every collection class is implemented based on some
27 standard data structure hence for every requirement
28 ready-made method support is available being a
29 programmer we can use these methods directly
30 without writing the functionality on our own.
31 Differences between Arrays and Collections ?
4
Karrasankar158@gmail.com
Arrays Collections
1) Arrays are fixed in 1) Collections are growable in
size. nature.
2) Memory point of view 2) Memory point of view
arrays are not collections are highly
recommended to use. recommended to use.
3) Performance point of 3) Performance point of view
view arrays are collections are not
recommended to use. recommended to use.
4) Arrays can hold only 4) Collections can hold both
homogeneous data type homogeneous and
elements. heterogeneous elements.
5) There is no underlying 5) Every collection class is
data structure for arrays implemented based on some
and hence there is no standard data structure and
readymade method hence readymade method
support. support is available.
6) Arrays can hold both
6) Collections can hold only
primitives and object
objects but not primitives.
types.
1 Collection:
2 If we want to represent a group of objects as single entity
3 then we should go for collections.
4 Collection framework:
5 It defines several classes and interfaces to represent a
6 group of objects as a single entity.
Java C++
5
Karrasankar158@gmail.com
Collection Containers
Collection framework STL(Standard Template Library)
5
6
7
7
Karrasankar158@gmail.com
1 Diagram:
2
3
4
5
6 SortedSet:
7 1. It is the child interface of Set.
8 2. If we want to represent a group of individual objects
9 as single entity "where duplicates are not allow but all
10 objects will be insertion according to some sorting
11 order then we should go for SortedSet.
12 (or)
13 3. If we want to represent a group of "unique objects"
14 according to some sorting order then we should go for
15 SortedSet.
16 NavigableSet:
17 1. It is the child interface of SortedSet.
18 2. It provides several methods for navigation purposes.
8
Karrasankar158@gmail.com
1 Queue:
2 1. It is the child interface of Collection.
3 2. If we want to represent a group of individual
4 objects prior to processing then we should go for
5 queue concept.
6 Diagram:
7
8
9
10
11
12
13
14 SortedMap:
15 1. It is the child interface of Map.
10
Karrasankar158@gmail.com
11
Karrasankar158@gmail.com
1
2
3
4 Diagram:
5
12
Karrasankar158@gmail.com
1
2
3
4 Collection interface:
5 • If we want to represent a group of individual objects
6 as a single entity then we should go for Collection
7 interface. This interface defines the most common
8 general methods which can be applicable for any
9 Collection object.
10 • The following is the list of methods present in
11 Collection interface.
12 1. boolean add(Object o);
13 2. boolean addAll(Collection c);
14 3. boolean remove(Object o);
15 4. boolean removeAll(Object o);
16 5. boolean retainAll(Collection c);
17 To remove all objects except those present in c.
18 6. Void clear();
19 7. boolean contains(Object o);
13
Karrasankar158@gmail.com
27 ArrayList:
14
Karrasankar158@gmail.com
15
Karrasankar158@gmail.com
1
2 System.out.println(a1 instanceof RandomAccess);
3 //true
4 System.out.println(a2 instanceof RandomAccess);
5 //false
6
7
8
ArrayList Vector
1) No method is 1) Every method is
synchronized synchronized
2) At a time multiple Threads 2) At a time only one
are allow to operate on Thread is allow to operate
ArrayList object and hence on Vector object and hence
ArrayList object is not Vector object is Thread
Thread safe. safe.
3) Relatively performance is 3) Relatively performance
high because Threads are not is low because Threads are
required to wait. required to wait.
4) It is non legacy and 4) It is legacy and
introduced in 1.2v introduced in 1.0v
17
Karrasankar158@gmail.com
14
15 LinkedList:
16 1. The underlying data structure is double LinkedList
18
Karrasankar158@gmail.com
13
14
15
16
19
Karrasankar158@gmail.com
1 3. Object getFirst();
2 4. Object getLast();
3 5. Object removeFirst();
4 6. Object removeLast();
5 We can apply these methods only on LinkedList object.
6 Constructors:
7 1. LinkedList l=new LinkedList();
8 Creates an empty LinkedList object.
9 2. LinkedList l=new LinkedList(Collection c);
10 To create an equivalent LinkedList object for the
11 given collection.
12 Example:
13 import java.util.*;
14 class LinkedListDemo
15 {
16 public static void main(String[] args)
17 {
18 LinkedList l=new LinkedList();
19 l.add("ashok");
20 l.add(30);
21 l.add(null);
22 l.add("ashok");
23 System.out.println(l);//[ashok, 30,
24 null, ashok]
25 l.set(0,"software");
26 System.out.println(l);//[software, 30,
27 null, ashok]
28 l.set(0,"venky");
29 System.out.println(l);//[venky, 30,
30 null, ashok]
31 l.removeLast();
32 System.out.println(l);//[venky, 30,
33 null]
34 l.addFirst("vvv");
20
Karrasankar158@gmail.com
1 System.out.println(l);//[vvv, venky,
2 30, null]
3 }
4 }
5 Vector:
6 1. The underlying data structure is resizable array (or)
7 growable array.
8 2. Duplicate objects are allowed.
9 3. Insertion order is preserved.
10 4. Heterogeneous objects are allowed.
11 5. Null insertion is possible.
12 6. Implements Serializable, Cloneable and
13 RandomAccess interfaces.
14 Every method present in Vector is synchronized and hence
15 Vector is Thread safe.
16 Vector specific methods:
17 To add objects:
18 1. add(Object o);-----Collection
19 2. add(int index,Object o);-----List
20 3. addElement(Object o);-----Vector
21 To remove elements:
22 1. remove(Object o);--------Collection
23 2. remove(int index);--------------List
24 3. removeElement(Object o);----Vector
25 4. removeElementAt(int index);-----Vector
26 5. removeAllElements();-----Vector
27 6. clear();-------Collection
21
Karrasankar158@gmail.com
1 To get objects:
2 1. Object get(int index);---------------List
3 2. Object elementAt(int index);-----Vector
4 3. Object firstElement();--------------Vector
5 4. Object lastElement();---------------Vector
6 Other methods:
7 1. Int size();//How many objects are added
8 2. Int capacity();//Total capacity
9 3. Enumeration elements();
10 Constructors:
11 1. Vector v=new Vector();
12 o Creates an empty Vector object with default
22
Karrasankar158@gmail.com
1 for(int i=1;i<=10;i++)
2 {
3 v.addElement(i);
4 }
5 System.out.println(v.capacity());//10
6 v.addElement("A");
7 System.out.println(v.capacity());//20
8 System.out.println(v);//[1, 2, 3, 4, 5, 6, 7,
9 8, 9, 10, A]
10 }
11 }
12 Stack:
13 1. It is the child class of Vector.
14 2. Whenever last in first out(LIFO) order required then
15 we should go for Stack.
16 Constructor:
17 It contains only one constructor.
18 Stack s= new Stack();
19 Methods:
20 1. Object push(Object o);
21 To insert an object into the stack.
22 2. Object pop();
23 To remove and return top of the stack.
24 3. Object peek();
25 To return top of the stack without removal.
26 4. boolean empty();
27 Returns true if Stack is empty.
23
Karrasankar158@gmail.com
24
Karrasankar158@gmail.com
1 }
2 }
3 Limitations of Enumeration:
4 1. We can apply Enumeration concept only for legacy
5 classes and it is not a universal cursor.
6 2. By using Enumeration we can get only read access
7 and we can't perform remove operations.
8 3. To overcome these limitations sun people introduced
9 Iterator concept in 1.2v.
10 Iterator:
11 1. We can use Iterator to get objects one by one from
12 any collection object.
13 2. We can apply Iterator concept for any collection
14 object and it is a universal cursor.
15 3. While iterating the objects by Iterator we can perform
16 both read and remove operations.
17 We can get Iterator object by using iterator() method of
18 Collection interface.
19 public Iterator iterator();
20 Iterator itr=c.iterator();
21 Iterator interface defines the following 3 methods.
22 1. public boolean hasNext();
23 2. public object next();
24 3. public void remove();
25 Example:
26 import java.util.*;
27 class IteratorDemo
26
Karrasankar158@gmail.com
1 {
2 public static void main(String[] args)
3 {
4 ArrayList a=new ArrayList();
5 for(int i=0;i<=10;i++)
6 {
7 a.add(i);
8 }
9 System.out.println(a);//[0, 1, 2, 3, 4,
10 5, 6, 7, 8, 9, 10]
11 Iterator itr=a.iterator();
12 while(itr.hasNext())
13 {
14 Integer i=(Integer)itr.next();
15 if(i%2==0)
16 System.out.println(i);//0, 2,
17 4, 6, 8, 10
18 else
19 itr.remove();
20 }
21 System.out.println(a);//[0, 2, 4, 6, 8,
22 10]
23 }
24 }
25 Limitations of Iterator:
26 1. Both enumeration and Iterator are single direction
27 cursors only. That is we can always move only
28 forward direction and we can't move to the backward
29 direction.
30 2. While iterating by Iterator we can perform only read
31 and remove operations and we can't perform
32 replacement and addition of new objects.
33 3. To overcome these limitations sun people introduced
34 listIterator concept.
35 ListIterator:
27
Karrasankar158@gmail.com
28
Karrasankar158@gmail.com
1 l.add("venki");
2 l.add("chiru");
3 l.add("nag");
4 System.out.println(l);//[balakrishna,
5 venki, chiru, nag]
6 ListIterator itr=l.listIterator();
7 while(itr.hasNext())
8 {
9 String s=(String)itr.next();
10 if(s.equals("venki"))
11 {
12 itr.remove();
13 }
14 }
15 System.out.println(l);//[balakrishna,
16 chiru, nag]
17 }
18 }
19 Case 1:
20 if(s.equals("chiru"))
21 {
22 itr.set("chran");
23 }
24 Output:
25 [balakrishna, venki, chiru, nag]
26 [balakrishna, venki, chran, nag]
27 Case 2:
28 if(s.equals("nag"))
29 {
30 itr.add("chitu");
31 }
32 Output:
33 [balakrishna, venki, chiru, nag]
34 [balakrishna, venki, chiru, nag, chitu]
35 The most powerful cursor is listIterator but its limitation is
36 it is applicable only for "List objects".
37 Compression of Enumeration Iterator and
38 ListIterator ?
29
Karrasankar158@gmail.com
Enumeratio
Property Iterator ListIterator
n
1) Is it
Yes no no
legacy ?
Applicable
2) It is
Only legacy for any Applicable for
applicable
classes. collection only list objects.
for ?
object.
Single Single
3) direction direction
Bi-directional.
Moment? cursor(forwar cursor(forw
d) ard)
By using By using By using
4) How to
elements() iterator()met listIterator()
get it?
method. hod. method.
5)
Both read Read/remove/repla
Accessibil Only read.
and remove. ce/add.
ity?
hasMoreEle
hasNext()
6) ment()
next() 9 methods.
Methods nextElement(
remove()
)
1 Set interface:
2 1. It is the child interface of Collection.
3 2. If we want to represent a group of individual objects
4 as a single entity where duplicates are not allow and
5 insertion order is not preserved then we should go for
6 Set interface.
30
Karrasankar158@gmail.com
1 Diagram:
2
3
4
5
31
Karrasankar158@gmail.com
32
Karrasankar158@gmail.com
1 }
2 }
3 LinkedHashSet:
4 1. It is the child class of HashSet.
5 2. LinkedHashSet is exactly same as HashSet except the
6 following differences.
HashSet LinkedHashSet
1) The underlying 1) The underlying data structure is
data structure is a combination of LinkedList and
Hashtable. Hashtable.
2) Insertion order is
2) Insertion order is preserved.
not preserved.
3) Introduced in 1.2
3) Introduced in 1.4v.
v.
7 In the above program if we are replacing HashSet with
8 LinkedHashSet the output is [B, C, D, Z, null, 10].That is
9 insertion order is preserved.
10 Example:
11 import java.util.*;
12 class LinkedHashSetDemo
13 {
14 public static void main(String[] args)
15 {
16 LinkedHashSet h=new LinkedHashSet();
17 h.add("B");
18 h.add("C");
19 h.add("D");
20 h.add("Z");
21 h.add(null);
22 h.add(10);
23 System.out.println(h.add("Z"));//false
33
Karrasankar158@gmail.com
1 System.out.println(h);//[B, C, D, Z,
2 null, 10]
3 }
4 }
34
Karrasankar158@gmail.com
7
8
9
10 TreeSet:
11 1. The underlying data structure is balanced tree.
12 2. Duplicate objects are not allowed.
13 3. Insertion order is not preserved and it is based on
14 some sorting order of objects.
15 4. Heterogeneous objects are not allowed if we are
16 trying to insert heterogeneous objects then we will get
17 ClassCastException.
18 5. Null insertion is possible(only once).
19 Constructors:
35
Karrasankar158@gmail.com
29 Null acceptance:
30 • For the empty TreeSet as the 1st element "null"
31 insertion is possible but after inserting that null if we
32 are trying to insert any other we will get
33 NullPointerException.
36
Karrasankar158@gmail.com
37
Karrasankar158@gmail.com
1 Comparable interface:
2 Comparable interface present in java.lang package and
3 contains only one method compareTo() method.
4 public int compareTo(Object obj);
5 Example:
6 obj1.compareTo(obj2);
7 Diagram:
8
9
10
11
12 Example 3:
13 class Test
14 {
15 public static void main(String[] args)
16 {
17
18 System.out.println("A".compareTo("Z"));//-25
19
20 System.out.println("Z".compareTo("K"));//15
21
22 System.out.println("A".compareTo("A"));//0
23 //System.out.println("A".compareTo(new
24 Integer(10)));
25 //Test.java:8:
26 compareTo(java.lang.String) in java.lang.String
27 cannot
28 be applied to (java.lang.Integer)
38
Karrasankar158@gmail.com
1
2 //System.out.println("A".compareTo(null));//N
3 ullPointerException
4 }
5 }
39
Karrasankar158@gmail.com
1
2
3
40
Karrasankar158@gmail.com
1
2
3
41
Karrasankar158@gmail.com
1 }
2 }
3 class MyComparator implements Comparator
4 {
5 public int compare(Object obj1,Object obj2)
6 {
7 Integer i1=(Integer)obj1;
8 Integer i2=(Integer)obj2;
9 if(i1<i2)
10 return +1;
11 else if(i1 > i2)
12 return -100;
13 else return 0;
14 }
15 }
42
Karrasankar158@gmail.com
1
2
3
4 Various alternative implementations of compare()
5 method:
6 public int compare(Object obj1,Object obj2)
7 {
8 Integer i1=(Integer)obj1;
9 Integer i2=(Integer)obj2;
10 //return i1.compareTo(i2);//[0, 5, 10,
11 15, 20]
12 //return -i1.compareTo(i2);//[20, 15,
13 10, 5, 0]
14 //return i2.compareTo(i1);//[20, 15,
15 10, 5, 0]
16 //return -i2.compareTo(i1);//[0, 5, 10,
17 15, 20]
18 //return -1;//[20, 5, 15, 0,
19 10]//reverse of insertion order
20 //return +1;//[10, 0, 15, 5,
21 20]//insertion order
22 //return 0;//[10]and all the remaining
23 elements treated as duplicate.
24 }
25 Requirement: Write a program to insert String objects
26 into the TreeSet where the sorting order is reverse of
27 alphabetical order.
28 Program:
43
Karrasankar158@gmail.com
1 import java.util.*;
2 class TreeSetDemo
3 {
4 public static void main(String[] args)
5 {
6 TreeSet t=new TreeSet(new
7 MyComparator());
8 t.add("Roja");
9 t.add("ShobaRani");
10 t.add("RajaKumari");
11 t.add("GangaBhavani");
12 t.add("Ramulamma");
13 System.out.println(t);//[ShobaRani,
14 Roja, Ramulamma, RajaKumari, GangaBhavani]
15 }
16 }
17 class MyComparator implements Comparator
18 {
19 public int compare(Object obj1,Object obj2)
20 {
21 String s1=obj1.toString();
22 String s2=(String)obj2;
23 //return s2.compareTo(s1);
24 return -s1.compareTo(s2);
25 }
26 }
27 Requirement: Write a program to insert StringBuffer
28 objects into the TreeSet where the sorting order is
29 alphabetical order.
30 Program:
31 import java.util.*;
32 class TreeSetDemo
33 {
34 public static void main(String[] args)
35 {
36 TreeSet t=new TreeSet(new
37 MyComparator());
38 t.add(new StringBuffer("A"));
39 t.add(new StringBuffer("Z"));
40 t.add(new StringBuffer("K"));
44
Karrasankar158@gmail.com
1 t.add(new StringBuffer("L"));
2 System.out.println(t);// [A, K, L, Z]
3 }
4 }
5 class MyComparator implements Comparator
6 {
7 public int compare(Object obj1,Object obj2)
8 {
9 String s1=obj1.toString();
10 String s2=obj2.toString();
11 return s1.compareTo(s2);
12 }
13 }
14 Note: Whenever we are defining our own customized
15 sorting by Comparator then the objects need not be
16 Comparable.
17 Example: StringBuffer
18 Requirement: Write a program to insert String and
19 StringBuffer objects into the TreeSet where the sorting
20 order is increasing length order. If 2 objects having the
21 same length then consider they alphabetical order.
22 Program:
23 import java.util.*;
24 class TreeSetDemo
25 {
26 public static void main(String[] args)
27 {
28 TreeSet t=new TreeSet(new
29 MyComparator());
30 t.add("A");
31 t.add(new StringBuffer("ABC"));
32 t.add(new StringBuffer("AA"));
33 t.add("xx");
34 t.add("ABCD");
35 t.add("A");
36 System.out.println(t);//[A, AA, xx,
37 ABC, ABCD]
38 }
45
Karrasankar158@gmail.com
1 }
2 class MyComparator implements Comparator
3 {
4 public int compare(Object obj1,Object obj2)
5 {
6 String s1=obj1.toString();
7 String s2=obj2.toString();
8 int l1=s1.length();
9 int l2=s2.length();
10 if(l1 < l2)
11 return -1;
12 else if(l1 > l2)
13 return 1;
14 else
15 return s1.compareTo(s2);
16 }
17 }
18 Note: If we are depending on default natural sorting order
19 then the objects should be "homogeneous and
20 comparable" otherwise we will get ClassCastException. If
21 we are defining our own sorting by Comparator then
22 objects "need not be homogeneous and comparable".
23 Comparable vs Comparator:
24 • For predefined Comparable classes default natural
25 sorting order is already available if we are not
26 satisfied with default natural sorting order then we can
27 define our own customized sorting order by
28 Comparator.
29 • For predefined non Comparable classes [like
30 StringBuffer] default natural sorting order is not
31 available we can define our own sorting order by
32 using Comparator object.
33 • For our own classes [like Customer, Student, and
34 Employee] we can define default natural sorting order
46
Karrasankar158@gmail.com
47
Karrasankar158@gmail.com
1) Comparable meant
1) Comparator meant for
for default natural
customized sorting order.
sorting order.
2) Present in java.lang
2) Present in java.util package.
package.
3) Contains only one 3) Contains 2 methods.
method. Compare() method.
compareTo() method. Equals() method.
4) String class and all 4) The only implemented classes
wrapper Classes of Comparator are Collator and
implements RuleBasedCollator. (used in
Comparable interface. GUI)
TreeSet as
the 1st
element null
insertion is
possible in
all other
cases we will
get NPE.
1 Map:
2
3 Diagram:
4
5
6
7
8
7
8
9
51
Karrasankar158@gmail.com
52
Karrasankar158@gmail.com
20 HashMap:
21 1. The underlying data structure is Hashtable.
22 2. Duplicate keys are not allowed but values can be
23 duplicated.
24 3. Insertion order is not preserved and it is based on hash
25 code of the keys.
26 4. Heterogeneous objects are allowed for both key and
27 value.
28 5. Null is allowed for keys(only once) and for
29 values(any number of times).
30 6. It is best suitable for Search operations.
31 Differences between HashMap and Hashtable ?
53
Karrasankar158@gmail.com
HashMap Hashtable
1) No method is 1) Every method is
synchronized. synchronized.
2) Multiple Threads can
2) Multiple Threads can't
operate simultaneously
operate simultaneously on
on HashMap object and
Hashtable object and hence
hence it is not Thread
Hashtable object is Thread safe.
safe.
3) Relatively 3) Relatively performance is
performance is high. low.
4) Null is not allowed for both
4) Null is allowed for
key and value otherwise we will
both key and value.
get NullPointerException.
5) It is non legacy and 5) It is legacy and introduced in
introduced in 1.2v. 1.0v.
54
Karrasankar158@gmail.com
55
Karrasankar158@gmail.com
1 //nagarjuna......500
2 //venkatesh......200 //
3 //balaiah......800
4 //chiranjeevi......100
5
6 if(m1.getKey().equals("nagarjuna"))
7 {
8 m1.setValue(1000);
9 }
10 }
11 System.out.println(m);
12
13 //{nagarjuna=1000,venkatesh=200,balaiah=800,chiran
14 jeevi=100}
15 }
16 }
17 LinkedHashMap:
18
19 It is exactly same as HashMap except the following
20 differences :
HashMap LinkedHashMap
1) The underlying 1) The underlying data structure is
data structure is a combination of Hashtable+
Hashtable. LinkedList.
2) Insertion order is
2) Insertion order is preserved.
not preserved.
3) introduced in
3) Introduced in 1.4v.
1.2.v.
21 Note: in the above program if we are replacing HashMap
22 with LinkedHashMap then the output is {chiranjeevi=100,
23 balaiah......800, venkatesh......200, nagarjuna......1000}
24 that is insertion order is preserved.
56
Karrasankar158@gmail.com
57
Karrasankar158@gmail.com
6 WeakHashMap:
7 It is exactly same as HashMap except the following
8 differences:
9 • In the case of normal HashMap, an object is not
10 eligible for GC even though it doesn't have any
11 references if it is associated with HashMap. That is
12 HashMap dominates garbage collector.
13 • But in the case of WeakHashMap if an object does not
14 have any references then it's always eligible for GC
15 even though it is associated with WeakHashMap that
16 is garbage collector dominates WeakHashMap.
17 Example:
18 import java.util.*;
19 class WeakHashMapDemo
20 {
21 public static void main(String[] args)throws
22 Exception
23 {
24 WeakHashMap m=new WeakHashMap();
25 Temp t=new Temp();
26 m.put(t,"ashok");
27 System.out.println(m);//{Temp=ashok}
28 t=null;
29 System.gc();
30 Thread.sleep(5000);
31 System.out.println(m);//{}
32 }
58
Karrasankar158@gmail.com
1 }
2 class Temp
3 {
4 public String toString()
5 {
6 return "Temp";
7 }
8 public void finalize()
9 {
10 System.out.println("finalize() method
11 called");
12 }
13 }
14 Output:
15 {Temp=ashok}
16 finalize() method called
17 {}
18 Diagram:
19
20
21
59
Karrasankar158@gmail.com
1
2 In the above program if we replace WeakHashMap with
3 normal HashMap then object won't be destroyed by the
4 garbage collector in this the output is
5
6 {Temp=ashok}
7 {Temp=ashok}
8 SortedMap:
9 • It is the child interface of Map.
10 • If we want to represent a group of key-value pairs
11 according to some sorting order of keys then we
12 should go for SortedMap.
13 • Sorting is possible only based on the keys but not
14 based on values.
15 • SortedMap interface defines the following 6
16 specific methods.
17 1. Object firsyKey();
18 2. Object lastKey();
19 3. SortedMap headMap(Object key);
20 4. SortedMap tailMap(Object key);
21 5. SortedMap subMap(Object key1,Object key2);
22 6. Comparator comparator();
23 TreeMap:
24 1. The underlying data structure is RED-BLACK Tree.
25 2. Duplicate keys are not allowed but values can be
26 duplicated.
27 3. Insertion order is not preserved and all entries will be
28 inserted according to some sorting order of keys.
60
Karrasankar158@gmail.com
61
Karrasankar158@gmail.com
1 t.put(103,"YYY");
2 t.put(101,"XXX");
3 t.put(104,106);
4 t.put(107,null);
5
6 //t.put("FFF","XXX");//ClassCastException
7
8 //t.put(null,"xxx");//NullPointerException
9 System.out.println(t);//{100=ZZZ,
10 101=XXX, 103=YYY, 104=106, 107=null}
11 }
12 }
13 Example 2:
14 import java.util.*;
15 class TreeMapDemo
16 {
17 public static void main(String[] args)
18 {
19 TreeMap t=new TreeMap(new
20 MyComparator());
21 t.put("XXX",10);
22 t.put("AAA",20);
23 t.put("ZZZ",30);
24 t.put("LLL",40);
25 System.out.println(t);//{ZZZ=30,
26 XXX=10, LLL=40, AAA=20}
27 }
28 }
29 class MyComparator implements Comparator
30 {
31 public int compare(Object obj1,Object obj2)
32 {
33 String s1=obj1.toString();
34 String s2=obj2.toString();
35 return s2.compareTo(s1);
36 }
37 }
38 Hashtable:
62
Karrasankar158@gmail.com
63
Karrasankar158@gmail.com
1 System.out.println(h);//{6=C, 16=F,
2 5=A, 15=D, 2=B, 23=E}
3 }
4 }
5 class Temp
6 {
7 int i;
8 Temp(int i)
9 {
10 this.i=i;
11 }
12 public int hashCode()
13 {
14 return i;
15 }
16 public String toString()
17 {
18 return i+"";
19 }
20 }
21 Diagram:
22
64
Karrasankar158@gmail.com
1
2
3
4 Note: if we change hasCode() method of Temp class as
5 follows.
6 public int hashCode()
7 {
8 return i%9;
9 }
10 Then the output is {16=F, 15=D, 6=C, 23=E, 5=A,
11 2=B}.
12 Diagram:
13
65
Karrasankar158@gmail.com
1
2
3
4 Note: if we change initial capacity as 25.
5 Hashtable h=new Hashtable(25);
6 output is : { 23=E, 16=F, 15=D, 6=C, 5=A, 2=B }
7 Diagram:
8
66
Karrasankar158@gmail.com
67
Karrasankar158@gmail.com
1
2
3
4 Properties:
5 1. Properties class is the child class of Hashtable.
6 2. In our program if anything which changes frequently
7 like DBUserName, Password etc., such type of values
8 not recommended to hardcode in java application
9 because for every change we have to recompile,
10 rebuild and redeployed the application and even
11 server restart also required sometimes it creates a big
12 business impact to the client.
13 3. Such type of variable things we have to hardcode in
14 property files and we have to read the values from the
15 property files into java application.
16 4. The main advantage in this approach is if there is any
17 change in property files automatically those changes
18 will be available to java application just redeployment
19 is enough.
20 5. By using Properties object we can read and hold
21 properties from property files into java application.
22 Constructor:
23 Properties p=new Properties();
24 In properties both key and value "should be String type
25 only".
26 Methods:
27 1. String getPrperty(String propertyname) ;
28 Returns the value associated with specified property.
68
Karrasankar158@gmail.com
15
16
17
18 Example:
19 import java.util.*;
20 import java.io.*;
21 class PropertiesDemo
22 {
23 public static void main(String[] args)throws
24 Exception
69
Karrasankar158@gmail.com
1 {
2 Properties p=new Properties();
3 FileInputStream fis=new
4 FileInputStream("abc.properties");
5 p.load(fis);
6 System.out.println(p);//{user=scott,
7 password=tiger, venki=8888}
8 String s=p.getProperty("venki");
9 System.out.println(s);//8888
10 p.setProperty("nag","9999999");
11 Enumeration e=p.propertyNames();
12 while(e.hasMoreElements())
13 {
14 String s1=(String)e.nextElement();
15 System.out.println(s1);//nag
16 //user
17 //password
18 //venki
19 }
20 FileOutputStream fos=new
21 FileOutputStream("abc.properties");
22 p.store(fos,"updated by ashok for scjp
23 demo class");
24 }
25 }
26 Property file:
27
28
29
30
31 Example:
32 import java.util.*;
70
Karrasankar158@gmail.com
1 import java.io.*;
2 class PropertiesDemo
3 {
4 public static void main(String[] args)throws
5 Exception
6 {
7 Properties p=new Properties();
8 FileInputStream fis=new
9 FileInputStream("db.properties");
10 p.load(fis);
11 String url=p.getProperty("url");
12 String user=p.getProperty("user");
13 String pwd=p.getProperty("pwd");
14 Connection
15 con=DriverManager.getConnection(url, user, pwd);
16 ---------------------------------------
17 ------------------
18 ---------------------------------------
19 -----------------
20 FileOutputStream fos=new
21 FileOutputStream("db.properties");
22 p.store(fos,"updated by ashok for scjp
23 demo class");
24 }
25 }
26
27
28
29 1.5 enhancements
30 Queue interface
31
32 Diagram:
33
71
Karrasankar158@gmail.com
1
2
3
72
Karrasankar158@gmail.com
74
Karrasankar158@gmail.com
1 System.out.println(q.poll());//0
2 System.out.println(q);//[1, 3, 2, 7, 4,
3 5, 6, 10, 8, 9]
4 }
5 }
6 Note: Some platforms may not provide proper supports for
7 PriorityQueue [windowsXP].
8
9 Example 2:
10 import java.util.*;
11 class PriorityQueueDemo
12 {
13 public static void main(String[] args)
14 {
15 PriorityQueue q=new
16 PriorityQueue(15,new MyComparator());
17 q.offer("A");
18 q.offer("Z");
19 q.offer("L");
20 q.offer("B");
21 System.out.println(q);//[Z, B, L, A]
22 }
23 }
24 class MyComparator implements Comparator
25 {
26 public int compare(Object obj1,Object obj2)
27 {
28 String s1=(String)obj1;
29 String s2=obj2.toString();
30 return s2.compareTo(s1);
31 }
32 }
33 1.6v Enhancements :
34 NavigableSet:
35 1. It is the child interface of SortedSet.
75
Karrasankar158@gmail.com
4
5
6
7 NavigableSet interface defines the following methods.
8 1. ceiling(e);
9 It returns the lowest element which is >=e.
10 2. higher(e);
11 It returns the lowest element which is >e.
12 3. floor(e);
13 It returns highest element which is <=e.
14 4. lower(e);
15 It returns height element which is <e.
16 5. pollFirst ();
17 Remove and return 1st element.
76
Karrasankar158@gmail.com
1 6. pollLast ();
2 Remove and return last element.
3 7. descendingSet ();
4 Returns SortedSet in reverse order.
5 Diagram:
6
7
8
9
10 Example:
11 import java.util.*;
12 class NavigableSetDemo
13 {
14 public static void main(String[] args)
15 {
16 TreeSet<Integer> t=new
17 TreeSet<Integer>();
18 t.add(1000);
19 t.add(2000);
20 t.add(3000);
21 t.add(4000);
22 t.add(5000);
23 System.out.println(t);//[1000, 2000,
24 3000, 4000, 5000]
25
26 System.out.println(t.ceiling(2000));//2000
77
Karrasankar158@gmail.com
1
2 System.out.println(t.higher(2000));//3000
3
4 System.out.println(t.floor(3000));//3000
5
6 System.out.println(t.lower(3000));//2000
7
8 System.out.println(t.pollFirst());//1000
9 System.out.println(t.pollLast());//5000
10
11 System.out.println(t.descendingSet());//[4000
12 , 3000, 2000]
13 System.out.println(t);//[2000, 3000,
14 4000]
15 }
16 }
17 NavigableMap:
18 It is the child interface of SortedMap and it defines several
19 methods for navigation purpose.
20 Diagram:
21
22
23
78
Karrasankar158@gmail.com
1
2 NavigableMap interface defines the following methods.
3 1. ceilingKey(e);
4 2. higherKey(e);
5 3. floorKey(e);
6 4. lowerKey(e);
7 5. pollFirstEntry();
8 6. pollLastEntry();
9 7. descendingMap();
10 Example:
11 import java.util.*;
12 class NavigableMapDemo
13 {
14 public static void main(String[] args)
15 {
16 TreeMap<String,String> t=new
17 TreeMap<String,String>();
18 t.put("b","banana");
19 t.put("c","cat");
20 t.put("a","apple");
21 t.put("d","dog");
22 t.put("g","gun");
23 System.out.println(t);//{a=apple,
24 b=banana, c=cat, d=dog, g=gun}
25
26 System.out.println(t.ceilingKey("c"));//c
27
28 System.out.println(t.higherKey("e"));//g
29 System.out.println(t.floorKey("e"));//d
30 System.out.println(t.lowerKey("e"));//d
31
32 System.out.println(t.pollFirstEntry());//a=ap
33 ple
34
35 System.out.println(t.pollLastEntry());//g=gun
79
Karrasankar158@gmail.com
1
2 System.out.println(t.descendingMap());//{d=do
3 g, c=cat, b=banana}
4 System.out.println(t);//{b=banana,
5 c=cat, d=dog}
6 }
7 }
8 Diagram:
9
10
11
12
13 Collections class:
14 Collections class defines several utility methods for
15 collection objects.
16 Sorting the elements of a List:
17 Collections class defines the following methods to perform
18 sorting the elements of a List.
20•
19 Questions and answer
22•
21 Interview Question
24•
23 Data Structures
26•
25 Indexed
28•
27 Duplicate
30•
29 Biology questions and answers
80
Karrasankar158@gmail.com
2•
1 Play
4•
3 Agenda
6•
5 Arraylist
7• Arrays
9•
8 Questions and answer
11•
10 Interview Question
13•
12 Data Structures
15•
14 Indexed
17•
16 Duplicate
19•
18 Biology questions and answers
21•
20 Play
23•
22 Agenda
25•
24 Arraylist
26• Arrays
27 public static void sort(List l);
28 • To sort the elements of List according to default
29 natural sorting order in this case the elements should
30 be homogeneous and comparable otherwise we will
31 get ClassCastException.
32 • The List should not contain null otherwise we will get
33 NullPointerException.
34 public static void sort(List l,Comparator c);
35 • To sort the elements of List according to customized
36 sorting order.
37 Program 1: To sort elements of List according to natural
38 sorting order.
39 import java.util.*;
40 class CollectionsDemo
41 {
42 public static void main(String[] args)
43 {
44 ArrayList l=new ArrayList();
45 l.add("Z");
46 l.add("A");
47 l.add("K");
48 l.add("N");
81
Karrasankar158@gmail.com
1 //l.add(new
2 Integer(10));//ClassCastException
3 //l.add(null);//NullPointerException
4 System.out.println("Before sorting
5 :"+l);//[Z, A, K, N]
6 Collections.sort(l);
7 System.out.println("After sorting
8 :"+l);//[A, K, N, Z]
9 }
10 }
11 Program 2: To sort elements of List according to
12 customized sorting order.
13 import java.util.*;
14 class CollectionsDemo
15 {
16 public static void main(String[] args)
17 {
18 ArrayList l=new ArrayList();
19 l.add("Z");
20 l.add("A");
21 l.add("K");
22 l.add("L");
23 l.add(new Integer(10));
24 //l.add(null);//NullPointerException
25 System.out.println("Before sorting
26 :"+l);//[Z, A, K, L, 10]
27 Collections.sort(l,new MyComparator());
28 System.out.println("After sorting
29 :"+l);//[Z, L, K, A, 10]
30 }
31 }
32 class MyComparator implements Comparator
33 {
34 public int compare(Object obj1,Object obj2)
35 {
36 String s1=(String)obj1;
37 String s2=obj2.toString();
38 return s2.compareTo(s1);
39 }
40 }
82
Karrasankar158@gmail.com
83
Karrasankar158@gmail.com
1 Diagram:
2
3
4
5 Program 2:
6 import java.util.*;
7 class CollectionsSearchDemo
8 {
9 public static void main(String[] args)
10 {
11 ArrayList l=new ArrayList();
12 l.add(15);
13 l.add(0);
14 l.add(20);
15 l.add(10);
16 l.add(5);
17 System.out.println(l);//[15, 0, 20, 10,
18 5]
19 Collections.sort(l,new MyComparator());
20 System.out.println(l);//[20, 15, 10, 5,
21 0]
22
23 System.out.println(Collections.binarySearch(l
24 ,10,new MyComparator()));//2
25
26 System.out.println(Collections.binarySearch(l
27 ,13,new MyComparator()));//-3
28
29 System.out.println(Collections.binarySearch(l
30 ,17));//-6
31 }
32 }
33 class MyComparator implements Comparator
34 {
35 public int compare(Object obj1,Object obj2)
84
Karrasankar158@gmail.com
1 {
2 Integer i1=(Integer)obj1;
3 Integer i2=(Integer)obj2;
4 return i2.compareTo(i1);
5 }
6 }
7 Diagram:
8
9
10
11
12 Conclusions:
13 1. Internally these search methods will use binary search
14 algorithm.
15 2. Successful search returns index unsuccessful search
16 returns insertion point.
17 3. Insertion point is the location where we can place the
18 element in the sorted list.
19 4. Before calling binarySearch() method compulsory the
20 list should be sorted otherwise we will get
21 unpredictable results.
22 5. If the list is sorted according to Comparator then at
23 the time of search operation also we should pass the
24 same Comparator object otherwise we will get
25 unpredictable results.
26 Note:
27 For the list of n elements with respect to binary Search()
28 method.
85
Karrasankar158@gmail.com
6
7
8
9 Reversing the elements of List:
10 public static void reverse(List l);
11
12 reverse() vs reverseOrder() method
13 • We can use reverse() method to reverse the elements
14 of List.
15 • Where as we can use reverseOrder() method to get
16 reversed Comparator.
17
18
19
86
Karrasankar158@gmail.com
1
2 Program: To reverse elements of list.
3 import java.util.*;
4 class CollectionsReverseDemo
5 {
6 public static void main(String[] args)
7 {
8 ArrayList l=new ArrayList();
9 l.add(15);
10 l.add(0);
11 l.add(20);
12 l.add(10);
13 l.add(5);
14 System.out.println(l);//[15, 0, 20, 10,
15 5]
16 Collections.reverse(l);
17 System.out.println(l);//[5, 10, 20, 0,
18 15]
19 }
20 }
21 Arrays class:
22 Arrays class defines several utility methods for arrays.
23 Sorting the elements of array:
24 • public static void sort(primitive[] p);//any primitive
25 data type we can give
26 To sort the elements of primitive array according to
27 default natural sorting order.
28 • public static void sort(object[] o);
29 To sort the elements of object[] array according to
30 default natural sorting order.
31 In this case objects should be homogeneous and
32 Comparable.
87
Karrasankar158@gmail.com
88
Karrasankar158@gmail.com
1 for(String s1:s)
2 {
3 System.out.println(s1);
4 }
5 Arrays.sort(s,new MyComparator());
6 System.out.println("Object array after
7 sorting by Comparator:");
8 for(String s1: s)
9 {
10 System.out.println(s1);
11 }
12 }
13 }
14 class MyComparator implements Comparator
15 {
16 public int compare(Object obj1,Object obj2)
17 {
18 String s1=obj1.toString();
19 String s2=obj2.toString();
20 return s2.compareTo(s1);
21 }
22 }
1 import java.util.*;
2 class ArraysSearchDemo
3 {
4 public static void main(String[] args)
5 {
6 int[] a={10,5,20,11,6};
7 Arrays.sort(a);
8
9 System.out.println(Arrays.binarySearch(a,6));
10 //1
11
12 System.out.println(Arrays.binarySearch(a,14))
13 ;//-5
14 String[] s={"A","Z","B"};
15 Arrays.sort(s);
16
17 System.out.println(Arrays.binarySearch(s,"Z")
18 );//2
19
20 System.out.println(Arrays.binarySearch(s,"S")
21 );//-3
22 Arrays.sort(s,new MyComparator());
23
24 System.out.println(Arrays.binarySearch(s,"Z",
25 new MyComparator()));//0
26
27 System.out.println(Arrays.binarySearch(s,"S",
28 new MyComparator()));//-2
29
30 System.out.println(Arrays.binarySearch(s,"N")
31 );//-4(unpredictable result)
32 }
33 }
90
Karrasankar158@gmail.com
91
Karrasankar158@gmail.com
1 }
2 }
3 Diagram:
4
92