Sunteți pe pagina 1din 92

Karrasankar158@gmail.

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 ?

24 o Getting synchronized version of ArrayList object

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

11 20. Comparable interface


12 21. compareTo() method analysis
13 22. Comparator interface
14 23. Compression of Comparable and Comparator ?
15 24. Compression of Set implemented class objects
16 25. Map
17 26. Entry interface
18 27. HashMap
19 o Differences between HashMap and Hashtable ?

20 o How to get synchronized version of HashMap

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

31 36. 1.6v Enhancements

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

6 ▪ Searching the elements of a List

7 ▪ Conclusions

8 o Arrays class
9 ▪ Sorting the elements of array

10 ▪ Searching the elements of array

11 ▪ Converting array to List

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)

1 9(Nine) key interfaces of collection


2 framework:
3 1. Collection
4 2. List
5 3. Set
6 4. SortedSet
7 5. NavigableSet
8 6. Queue
9 7. Map
10 8. SortedMap
11 9. NavigableMap
12 Collection:
13 1. If we want to represent a group of "individual objects"
14 as a single entity then we should go for collection.
15 2. In general we can consider collection as root interface
16 of entire collection framework.
17 3. Collection interface defines the most common
18 methods which can be applicable for any collection
19 object.
20 4. There is no concrete class which implements
21 Collection interface directly.
22 List:
23 1. It is the child interface of Collection.
24 2. If we want to represent a group of individual objects
25 as a single entity where "duplicates are allow and
6
Karrasankar158@gmail.com

1 insertion order must be preserved" then we should go


2 for List interface.
3 Diagram:
4

5
6
7

8 Vector and Stack classes are re-engineered in 1.2 versions


9 to implement List interface.
10 Set:
11 1. It is the child interface of Collection.
12 2. If we want to represent a group of individual objects
13 as single entity "where duplicates are not allow and
14 insertion order is not preserved" then we should go for
15 Set interface.

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 Note: All the above interfaces (Collection, List, Set,


12 SortedSet, NavigableSet, and Queue) meant for
13 representing a group of individual objects.
9
Karrasankar158@gmail.com

1 If we want to represent a group of objects as key-value


2 pairs then we should go for Map.
3 Map:
4 1. Map is not child interface of Collection.
5 2. If we want to represent a group of objects as key-
6 value pairs then we should go for Map interface.
7 3. Duplicate keys are not allowed but values can be
8 duplicated.
9 Diagram:
10

11
12
13

14 SortedMap:
15 1. It is the child interface of Map.

10
Karrasankar158@gmail.com

1 2. If we want to represent a group of objects as key value


2 pairs "according to some sorting order of keys" then
3 we should go for SortedMap.
4 NavigableMap:
5 1) It is the child interface of SortedMap and defines
6 several methods for navigation purposes.
7 What is the difference between Collection and
8 Collections ?
9 "Collection is an "interface" which can be used to
10 represent a group of objects as a single entity. Whereas
11 "Collections is an utility class" present in java.util package
12 to define several utility methods for Collection objects.
13 Collection--------------------interface
14 Collections------------------class
15 In collection framework the following are legacy
16 characters.
17 1. Enumeration(I)
18 2. Dictionary(AC)
19 3. Vector(C)
20 4. Stack(C)
21 5. Hashtable(C)
22 6. Properties(C)
23 Diagram:
24

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

1 8. boolean containsAll(Collection c);


2 9. boolean isEmpty();
3 10. Int size();
4 11. Object[] toArray();
5 12. Iterator iterator();
6 There is no concrete class which implements Collection
7 interface directly.
8 List interface:
9 • It is the child interface of Collection.
10 • If we want to represent a group of individual objects
11 as a single entity where duplicates are allow and
12 insertion order is preserved. Then we should go for
13 List.
14 • We can differentiate duplicate objects and we can
15 maintain insertion order by means of index hence
16 "index play very important role in List".
17 List interface defines the following specific methods.
18 1. boolean add(int index,Object o);
19 2. boolean addAll(int index,Collectio c);
20 3. Object get(int index);
21 4. Object remove(int index);
22 5. Object set(int index,Object new);//to replace
23 6. Int indexOf(Object o);
24 Returns index of first occurrence of "o".
25 7. Int lastIndexOf(Object o);
26 8. ListIterator listIterator();

27 ArrayList:
14
Karrasankar158@gmail.com

1 1. The underlying data structure is resizable array (or)


2 growable array.
3 2. Duplicate objects are allowed.
4 3. Insertion order preserved.
5 4. Heterogeneous objects are allowed.(except TreeSet ,
6 TreeMap every where heterogenious objects are
7 allowed)
8 5. Null insertion is possible.
9 Constructors:
10 1) ArrayList a=new ArrayList();
11 Creates an empty ArrayList object with default initial
12 capacity "10" if ArrayList reaches its max capacity then a
13 new ArrayList object will be created with
14 New capacity=(current capacity*3/2)+1
15 2) ArrayList a=new ArrayList(int initialcapacity);
16 Creates an empty ArrayList object with the specified initial
17 capacity.
18 3) ArrayList a=new ArrayList(collection c);
19 Creates an equivalent ArrayList object for the given
20 Collection that is this constructor meant for inter
21 conversation between collection objects. That is to dance
22 between collection objects.
23 Demo program for ArrayList:
24 import java.util.*;
25 class ArrayListDemo
26 {

15
Karrasankar158@gmail.com

1 public static void main(String[] args)


2 {
3 ArrayList a=new ArrayList();
4 a.add("A");
5 a.add(10);
6 a.add("A");
7 a.add(null);
8 System.out.println(a);//[A, 10, A,
9 null]
10 a.remove(2);
11 System.out.println(a);//[A, 10, null]
12 a.add(2,"m");
13 a.add("n");
14 System.out.println(a);//[A, 10, m,
15 null, n]
16 }
17 }

18 • Usually we can use collection to hold and transfer


19 objects from one tier to another tier. To provide
20 support for this requirement every Collection class
21 already implements Serializable and Cloneable
22 interfaces.
23 • ArrayList and Vector classes implements
24 RandomAccess interface so that any random element
25 we can access with the same speed. Hence ArrayList
26 is the best choice of "retrival operation".
27 • RandomAccess interface present in util package and
28 doesn't contain any methods. It is a marker interface.
29 Example :
30 ArrayList a1=new ArrayList();
31 LinkedList a2=new LinkedList();
32
33 System.out.println(a1 instanceof Serializable );
34 //true
35 System.out.println(a2 instanceof Clonable); //true
16
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

9 Differences between ArrayList and Vector ?

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

10 Getting synchronized version of ArrayList object:


11 • Collections class defines the following method to
12 return synchronized version of List.
13 Public static List synchronizedList(list l);
14 Example:

17
Karrasankar158@gmail.com

3 • Similarly we can get synchronized version of Set and


4 Map objects by using the following methods.
5 1) public static Set synchronizedSet(Set s);
6 2) public static Map synchronizedMap(Map m);
7 • ArrayList is the best choice if our frequent operation
8 is retrieval.
9 • ArrayList is the worst choice if our frequent operation
10 is insertion (or) deletion in the middle because it
11 requires several internal shift operations.
12 Diagram:
13

14

15 LinkedList:
16 1. The underlying data structure is double LinkedList
18
Karrasankar158@gmail.com

1 2. If our frequent operation is insertion (or) deletion in


2 the middle then LinkedList is the best choice.
3 3. If our frequent operation is retrieval operation then
4 LinkedList is worst choice.
5 4. Duplicate objects are allowed.
6 5. Insertion order is preserved.
7 6. Heterogeneous objects are allowed.
8 7. Null insertion is possible.
9 8. Implements Serializable and Cloneable interfaces but
10 not RandomAccess.
11 Diagram:
12

13
14
15
16

17 Usually we can use LinkedList to implement Stacks and


18 Queues.
19 To provide support for this requirement LinkedList class
20 defines the following 6 specific methods.
21 1. void addFirst(Object o);
22 2. void addLast(Object o);

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

13 initial capacity 10.


14 o Once Vector reaches its maximum capacity then

15 a new Vector object will be created with double


16 capacity. That is
17 "newcapacity=currentcapacity*2".
18 2. Vector v=new Vector(int initialcapacity);
19 3. Vector v=new Vector(int initialcapacity, int
20 incrementalcapacity);
21 4. Vector v=new Vector(Collection c);
22 Example:
23 import java.util.*;
24 class VectorDemo
25 {
26 public static void main(String[] args)
27 {
28 Vector v=new Vector();
29 System.out.println(v.capacity());//10

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

1 5. Int search(Object o);


2 Returns offset if the element is available otherwise
3 returns "-1"
4 Example:
5 import java.util.*;
6 class StackDemo
7 {
8 public static void main(String[] args)
9 {
10 Stack s=new Stack();
11 s.push("A");
12 s.push("B");
13 s.push("C");
14 System.out.println(s);//[A, B, C]
15 System.out.println(s.pop());//C
16 System.out.println(s);//[A, B]
17 System.out.println(s.peek());//B
18 System.out.println(s.search("A"));//2
19 System.out.println(s.search("Z"));//-1
20 System.out.println(s.empty());//false
21 }
22 }

23 The 3 cursors of java:


24 If we want to get objects one by one from the collection
25 then we should go for cursor. There are 3 types of cursors
26 available in java. They are:
27 1. Enumeration
28 2. Iterator
29 3. ListIterator
30 Enumeration:

24
Karrasankar158@gmail.com

1 1. We can use Enumeration to get objects one by one


2 from the legacy collection objects.
3 2. We can create Enumeration object by using
4 elements() method.
5 public Enumeration elements();
6 Enumeration e=v.elements();
7 using Vector Object
8 Enumeration interface defines the following two
9 methods
10 1. public boolean hasMoreElements();
11 2. public Object nextElement();
12 Example:
13 import java.util.*;
14 class EnumerationDemo
15 {
16 public static void main(String[] args)
17 {
18 Vector v=new Vector();
19 for(int i=0;i<=10;i++)
20 {
21 v.addElement(i);
22 }
23 System.out.println(v);//[0, 1, 2, 3, 4,
24 5, 6, 7, 8, 9, 10]
25 Enumeration e=v.elements();
26 while(e.hasMoreElements())
27 {
28 Integer
29 i=(Integer)e.nextElement();
30 if(i%2==0)
31 System.out.println(i);//0 2 4
32 6 8 10
33 }
34 System.out.print(v);//[0, 1, 2, 3, 4,
35 5, 6, 7, 8, 9, 10]
25
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

1 1. ListIterator is the child interface of Iterator.


2 2. By using listIterator we can move either to the
3 forward direction (or) to the backward direction that is
4 it is a bi-directional cursor.
5 3. While iterating by listIterator we can perform
6 replacement and addition of new objects in addition to
7 read and remove operations
8 By using listIterator method we can create listIterator
9 object.
10 public ListIterator listIterator();
11 ListIterator itr=l.listIterator();
12 (l is any List object)
13 ListIterator interface defines the following 9 methods.
14 1. public boolean hasNext();
15 2. public Object next(); forward
16 3. public int nextIndex();
17 4. public boolean hasPrevious();
18 5. public Object previous(); backward
19 6. public int previousIndex();
20 7. public void remove();
21 8. public void set(Object new);
22 9. public void add(Object new);
23 Example:
24 import java.util.*;
25 class ListIteratorDemo
26 {
27 public static void main(String[] args)
28 {
29 LinkedList l=new LinkedList();
30 l.add("balakrishna");

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

6 Set interface does not contain any new method we have to


7 use only Collection interface methods.
8 HashSet:
9 1. The underlying data structure is Hashtable.
10 2. Insertion order is not preserved and it is based on hash
11 code of the objects.
12 3. Duplicate objects are not allowed.
13 4. If we are trying to insert duplicate objects we won't
14 get compile time error and runtime error add() method
15 simply returns false.
16 5. Heterogeneous objects are allowed.
17 6. Null insertion is possible.(only once)
18 7. Implements Serializable and Cloneable interfaces but
19 not RandomAccess.

31
Karrasankar158@gmail.com

1 8. HashSet is best suitable, if our frequent operation is


2 "Search".
3 Constructors:
4 1. HashSet h=new HashSet();
5 Creates an empty HashSet object with default initial
6 capacity 16 and default fill ratio 0.75(fill ratio is also
7 known as load factor).
8 2. HashSet h=new HashSet(int initialcapacity);
9 Creates an empty HashSet object with the specified
10 initial capacity and default fill ratio 0.75.
11 3. HashSet h=new HashSet(int initialcapacity,float
12 fillratio);
13 4. HashSet h=new HashSet(Collection c);
14 Note : After filling how much ratio new HashSet object
15 will be created , The ratio is called "FillRatio" or
16 "LoadFactor".
17
18 Example:
19 import java.util.*;
20 class HashSetDemo
21 {
22 public static void main(String[] args)
23 {
24 HashSet h=new HashSet();
25 h.add("B");
26 h.add("C");
27 h.add("D");
28 h.add("Z");
29 h.add(null);
30 h.add(10);
31 System.out.println(h.add("Z"));//false
32 System.out.println(h);//[null, D, B, C,
33 10, Z]

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 }

5 Note: LinkedHashSet and LinkedHashMap commonly


6 used for implementing "cache applications" where
7 insertion order must be preserved and duplicates are not
8 allowed.
9 SortedSet:
10 1. It is child interface of Set.
11 2. If we want to represent a group of "unique objects"
12 where duplicates are not allowed and all objects must
13 be inserting according to some sorting order then we
14 should go for SortedSet interface.
15 3. That sorting order can be either default natural sorting
16 (or) customized sorting order.
17 SortedSet interface define the following 6 specific
18 methods.
19 1. Object first();
20 2. Object last();
21 3. SortedSet headSet(Object obj);
22 Returns the SortedSet whose elements are <obj.
23 4. SortedSet tailSet(Object obj);
24 It returns the SortedSet whose elements are >=obj.
25 5. SortedSet subset(Object o1,Object o2);
26 Returns the SortedSet whose elements are >=o1 but
27 <o2.
28 6. Comparator comparator();

34
Karrasankar158@gmail.com

1 o Returns the Comparator object that describes


2 underlying sorting technique.
3 o If we are following default natural sorting order
4 then this method returns null.
5 Diagram:
6

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

1 1. TreeSet t=new TreeSet();


2 Creates an empty TreeSet object where all elements
3 will be inserted according to default natural sorting
4 order.
5 2. TreeSet t=new TreeSet(Comparator c);
6 Creates an empty TreeSet object where all objects will
7 be inserted according to customized sorting order
8 specified by Comparator object.
9 3. TreeSet t=new TreeSet(SortedSet s);
10 4. TreeSet t=new TreeSet(Collection c);
11 Example 1:
12 import java.util.*;
13 class TreeSetDemo
14 {
15 public static void main(String[] args)
16 {
17 TreeSet t=new TreeSet();
18 t.add("A");
19 t.add("a");
20 t.add("B");
21 t.add("Z");
22 t.add("L");
23 //t.add(new
24 Integer(10));//ClassCastException
25 //t.add(null);//NullPointerException
26 System.out.println(t);//[A, B, L, Z, a]
27 }
28 }

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

1 • For the non empty TreeSet if we are trying to insert


2 null then we will get NullPointerException.
3 Example 2:
4 import java.util.*;
5 class TreeSetDemo
6 {
7 public static void main(String[] args)
8 {
9 TreeSet t=new TreeSet();
10 t.add(new StringBuffer("A"));
11 t.add(new StringBuffer("Z"));
12 t.add(new StringBuffer("L"));
13 t.add(new StringBuffer("B"));
14 System.out.println(t);
15 }
16 }
17 Output:
18 Runtime Exception.
19 Note :
20 • Exception in thread "main"
21 java.lang.ClassCastException: java.lang.StringBuffer
22 cannot be cast to java.lang.Comparable
23 • If we are depending on default natural sorting order
24 compulsory the objects should be homogeneous and
25 Comparable otherwise we will get
26 ClassCastException.
27 • An object is said to be Comparable if and only if the
28 corresponding class implements Comparable
29 interface.
30 • String class and all wrapper classes implements
31 Comparable interface but StringBuffer class doesn't
32 implement Comparable interface hence in the above
33 program we are getting ClassCastException.

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 }

6 If we are depending on default natural sorting order then


7 internally JVM will use compareTo() method to arrange
8 objects in sorting order.
9 Example 4:
10 import java.util.*;
11 class Test
12 {
13 public static void main(String[] args)
14 {
15 TreeSet t=new TreeSet();
16 t.add(10);
17 t.add(0);
18 t.add(15);
19 t.add(10);
20 System.out.println(t);//[0, 10, 15]
21 }
22 }

23 compareTo() method analysis:


24
25

39
Karrasankar158@gmail.com

1
2
3

4 • If we are not satisfying with default natural sorting


5 order (or) if default natural sorting order is not
6 available then we can define our own customized
7 sorting by Comparator object.
8 • Comparable meant for default natural sorting order.
9 • Comparator meant for customized sorting order.
10 Comparator interface:
11 Comparator interface present in java.util package this
12 interface defines the following 2 methods.
13 1) public int compare(Object obj1,Object Obj2);
14 Diagram:
15

40
Karrasankar158@gmail.com

1
2
3

4 2) public boolean equals(Object obj);


5 • Whenever we are implementing Comparator interface
6 we have to provide implementation only for
7 compare() method.
8 • Implementing equals() method is optional because it
9 is already available from Object class through
10 inheritance.
11 Requirement: Write a program to insert integer objects
12 into the TreeSet where the sorting order is descending
13 order.
14 Program:
15 import java.util.*;
16 class Test
17 {
18 public static void main(String[] args)
19 {
20 TreeSet t=new TreeSet(new
21 MyComparator()); //---->(1)
22 t.add(10);
23 t.add(0);
24 t.add(15);
25 t.add(5);
26 t.add(20);
27 System.out.println(t);//[20, 15, 10, 5,
28 0]

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 }

16 • At line "1" if we are not passing Comparator object


17 then JVM will always calls compareTo() method
18 which is meant for default natural sorting
19 order(ascending order)hence in this case the output is
20 [0, 5, 10, 15, 20].
21 • At line "1" if we are passing Comparator object then
22 JVM calls compare() method of MyComparator class
23 which is meant for customized sorting
24 order(descending order) hence in this case the output
25 is [20, 15, 10, 5, 0].
26 Diagram:
27

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

1 by using Comparable interface. The person who is


2 using our class, if he is not satisfied with default
3 natural sorting order then he can define his own
4 sorting order by using Comparator object.
5 Example:
6 import java.util.*;
7 class Employee implements Comparable
8 {
9 String name;
10 int eid;
11 Employee(String name,int eid)
12 {
13 this.name=name;
14 this.eid=eid;
15 }
16 public String toString()
17 {
18 return name+"----"+eid;
19 }
20 public int compareTo(Object o)
21 {
22 int eid1=this.eid;
23 int eid2=((Employee)o).eid;
24 if(eid1 < eid2)
25 {
26 return -1;
27 }
28 else if(eid1 > eid2)
29 {
30 return 1;
31 }
32 else return 0;
33 }
34 }
35 class CompComp
36 {
37 public static void main(String[] args)
38 {

47
Karrasankar158@gmail.com

1 Employee e1=new Employee("nag",100);


2 Employee e2=new
3 Employee("balaiah",200);
4 Employee e3=new Employee("chiru",50);
5 Employee e4=new Employee("venki",150);
6 Employee e5=new Employee("nag",100);
7 TreeSet t1=new TreeSet();
8 t1.add(e1);
9 t1.add(e2);
10 t1.add(e3);
11 t1.add(e4);
12 t1.add(e5);
13 System.out.println(t1);//[chiru----50,
14 nag----100, venki----150, balaiah----200]
15 TreeSet t2=new TreeSet(new
16 MyComparator());
17 t2.add(e1);
18 t2.add(e2);
19 t2.add(e3);
20 t2.add(e4);
21 t2.add(e5);
22 System.out.println(t2);//[balaiah----
23 200, chiru----50, nag----100, venki----150]
24 }
25 }
26 class MyComparator implements Comparator
27 {
28 public int compare(Object obj1,Object obj2)
29 {
30 Employee e1=(Employee)obj1;
31 Employee e2=(Employee)obj2;
32 String s1=e1.name;
33 String s2=e2.name;
34 return s1.compareTo(s2);
35 }
36 }

37 Compression of Comparable and Comparator ?


Comparable Comparator
48
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)

1 Compression of Set implemented class objects:


Property HashSet LinkedHashSet TreeSet
1) Underlying LinkedList + Balanced
Hashtable.
Data structure. Hashtable. Tree.
Not
2) Insertion Not
Preserved. preserved
order. preserved.
(by default).
3) Duplicate Not
Not allowed. Not allowed.
objects. allowed.
4) Sorting Not
Not applicable. Applicable.
order. applicable.
5)
Heterogeneous Allowed. Allowed. Not allowed.
objects.
6) Null For the
Allowed. Allowed.
insertion. empty
49
Karrasankar158@gmail.com

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

9 1. If we want to represent a group of objects as "key-


10 value" pair then we should go for Map interface.
50
Karrasankar158@gmail.com

1 2. Both key and value are objects only.


2 3. Duplicate keys are not allowed but values can be
3 duplicated
4 4. Each key-value pair is called "one entry".
5 Diagram:
6

7
8
9

10 • Map interface is not child interface of Collection and


11 hence we can't apply Collection interface methods
12 here.
13 • Map interface defines the following specific methods.
14 1. Object put(Object key,Object value);
15 To add an entry to the Map, if key is already available
16 then the old value replaced with new value and old

51
Karrasankar158@gmail.com

1 value will be returned.


2 Example:
3 2. import java.util.*;
4 3. class Map
5 4. {
6 5. public static void main(String[] args)
7 6. {
8 7. HashMap m=new HashMap();
9 8. m.put("100","vijay");
10 9.
11 System.out.println(m);//{100=vijay}
12 10. m.put("100","ashok");
13 11.
14 System.out.println(m);//{100=ashok}
15 12. }
16 13. }
17 14. void putAll(Map m);
18 15. Object get(Object key);
19 16. Object remove(Object key);
20 It removes the entry associated with specified key and
21 returns the corresponding value.
22 17. boolean containsKey(Object key);
23 18. boolean containsValue(Object value);
24 19. boolean isEmpty();
25 20. Int size();
26 21. void clear();
27 22. Set keySet();
28 The set of keys we are getting.
29 23. Collection values();
30 The set of values we are getting.
31 24. Set entrySet();
32 The set of entryset we are getting.
33 Entry interface:

52
Karrasankar158@gmail.com

1 Each key-value pair is called one entry. Hence Map is


2 considered as a group of entry Objects, without existing
3 Map object there is no chance of existing entry object
4 hence interface entry is define inside Map interface(inner
5 interface).
6 Example:
7 interface Map
8 {
9 .................;
10 .................;
11 .................;
12 interface Entry
13 {
14 Object getKey();
15 Object getValue(); on Entry
16 we can apply these 3 methods.
17 Object setValue(Object new);
18 }
19 }

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.

1 How to get synchronized version of HashMap:


2 By default HashMap object is not synchronized. But we
3 can get synchronized version by using the following
4 method of Collections class.
5 public static Map synchronizedMap(Map m1)
6 Constructors:
7 1. HashMap m=new HashMap();
8 Creates an empty HashMap object with default initial
9 capacity 16 and default fill ratio "0.75".
10 2. HashMap m=new HashMap(int initialcapacity);
11 3. HashMap m =new HashMap(int initialcapacity, float
12 fillratio);

54
Karrasankar158@gmail.com

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


2 Example:
3
4 import java.util.*;
5 class HashMapDemo
6 {
7 public static void main(String[] args)
8 {
9 HashMap m=new HashMap();
10 m.put("chiranjeevi",700);
11 m.put("balaiah",800);
12 m.put("venkatesh",200);
13 m.put("nagarjuna",500);
14
15 System.out.println(m);//{nagarjuna=500,venkat
16 esh=200,balaiah=800,chiranjeevi=700}
17
18 System.out.println(m.put("chiranjeevi",100));
19 //700
20 Set s=m.keySet();
21
22 System.out.println(s);//[nagarjuna,venkatesh,
23 balaiah,chiranjeevi]
24 Collection c=m.values();
25 System.out.println(c);//[500, 200, 800,
26 100]
27 Set s1=m.entrySet();
28
29 System.out.println(s1);//[nagarjuna=500,venka
30 tesh=200,balaiah=800,chiranjeevi=100]
31 Iterator itr=s1.iterator();
32 while(itr.hasNext())
33 {
34 Map.Entry
35 m1=(Map.Entry)itr.next();
36
37 System.out.println(m1.getKey()+"......"+m1.ge
38 tValue());

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

1 Note: in general we can use LinkedHashSet and


2 LinkedHashMap for implementing cache applications.
3 IdentityHashMap:
4
5 It is exactly same as HashMap except the following
6 differences:
7 1. In the case of HashMap JVM will always use
8 ".equals()"method to identify duplicate keys, which is
9 meant for content comparision.
10 2. But in the case of IdentityHashMap JVM will use==
11 (double equal operator) to identify duplicate keys,
12 which is meant for reference comparision.
13 Example:
14 import java.util.*;
15 class HashMapDemo
16 {
17 public static void main(String[] args)
18 {
19 HashMap m=new HashMap();
20 Integer i1=new Integer(10);
21 Integer i2=new Integer(10);
22 m.put(i1,"pavan");
23 m.put(i2,"kalyan");
24 System.out.println(m);
25 }
26 }

27 • In the above program i1 and i2 are duplicate keys


28 because i1.equals(i2) returns true.
29 • In the above program if we replace HashMap with
30 IdentityHashMap then i1 and i2 are not duplicate keys

57
Karrasankar158@gmail.com

1 because i1==i2 is false hence in this case the output is


2 {10=pavan, 10=kalyan}.
3 System.out.println(m.get(10));//null
4 10==i1------false
5 10==i2------false

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

1 4. If we are depending on default natural sorting order


2 keys should be homogeneous and Comparable
3 otherwise we will get ClassCastException.
4 5. If we are defining our own sorting order by
5 Comparator then keys can be heterogeneous and non
6 Comparable.
7 6. There are no restrictions on values they can be
8 heterogeneous and non Comparable.
9 7. For the empty TreeMap as first entry null key is
10 allowed but after inserting that entry if we are trying
11 to insert any other entry we will get
12 NullPointerException.
13 8. For the non empty TreeMap if we are trying to insert
14 an entry with null key we will get
15 NullPointerException.
16 9. There are no restrictions for null values.
17 Constructors:
18 1. TreeMap t=new TreeMap();
19 For default natural sorting order.
20 2. TreeMap t=new TreeMap(Comparator c);
21 For customized sorting order.
22 3. TreeMap t=new TreeMap(SortedMap m);
23 4. TreeMap t=new TreeMap(Map m);
24 Example 1:
25 import java.util.*;
26 class TreeMapDemo
27 {
28 public static void main(String[] args)
29 {
30 TreeMap t=new TreeMap();
31 t.put(100,"ZZZ");

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

1 1. The underlying data structure is Hashtable.


2 2. Insertion order is not preserved and it is based on hash
3 code of the keys.
4 3. Heterogeneous objects are allowed for both keys and
5 values.
6 4. Null key (or) null value is not allowed otherwise we
7 will get NullPointerException.
8 5. Duplicate keys are allowed but values can be
9 duplicated.
10 6. Every method present inside Hashtable is syncronized
11 and hence Hashtable objet is Thread-safe.
12 Constructors:
13 1. Hashtable h=new Hashtable();
14 Creates an empty Hashtable object with default
15 initialcapacity 11 and default fill ratio 0.75.
16 2. Hashtable h=new Hashtable(int initialcapacity);
17 3. Hashtable h=new Hashtable(int initialcapacity,float
18 fillratio);
19 4. Hashtable h=new Hashtable (Map m);
20 Example:
21 import java.util.*;
22 class HashtableDemo
23 {
24 public static void main(String[] args)
25 {
26 Hashtable h=new Hashtable();
27 h.put(new Temp(5),"A");
28 h.put(new Temp(2),"B");
29 h.put(new Temp(6),"C");
30 h.put(new Temp(15),"D");
31 h.put(new Temp(23),"E");
32 h.put(new Temp(16),"F");

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

1 2. String setproperty(String propertyname,String


2 propertyvalue);
3 To set a new property.
4 3. Enumeration propertyNames();
5 4. void load(InputStream is);//Any InputStream we can
6 pass.
7 To load Properties from property files into java
8 Properties object.
9 5. void store(OutputStream os,String comment);//Any
10 OutputStream we can pass.
11 To store the properties from Properties object into
12 properties file.
13 Diagram:
14

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

4 1. Queue is child interface of Collections.


5 2. If we want to represent a group of individual objects
6 prior (happening before something else) to processing
7 then we should go for Queue interface.
8 3. Usually Queue follows first in first out(FIFO) order
9 but based on our requirement we can implement our
10 own order also.
11 4. From 1.5v onwards LinkedList also implements
12 Queue interface.
13 5. LinkedList based implementation of Queue always
14 follows first in first out order.
15 Assume we have to send sms for one lakh mobile numbers
16 , before sending messages we have to store all mobile
17 numbers into Queue so that for the first inserted number
18 first message will be triggered(FIFO).
19 Queue interface methods:

72
Karrasankar158@gmail.com

1 1. boolean affer(Object o);


2 To add an object to the Queue.
3 2. Object poll() ;
4 To remove and return head element of the Queue, if
5 Queue is empty then we will get null.
6 3. Object remove();
7 To remove and return head element of the Queue. If
8 Queue is empty then this method raises Runtime
9 Exception saying NoSuchElementException.
10 4. Object peek();
11 To return head element of the Queue without removal,
12 if Queue is empty this method returns null.
13 5. Object element();
14 It returns head element of the Queue and if Queue is
15 empty then it will raise Runtime Exception saying
16 NoSuchElementException.
17 PriorityQueue:
18 1. PriorityQueue is a data structure to represent a group
19 of individual objects prior to processing according to
20 some priority.
21 2. The priority order can be either default natural sorting
22 order (or) customized sorting order specified by
23 Comparator object.
24 3. If we are depending on default natural sorting order
25 then the objects must be homogeneous and
26 Comparable otherwise we will get
27 ClassCastException.
28 4. If we are defining our own customized sorting order
29 by Comparator then the objects need not be
30 homogeneous and Comparable.
73
Karrasankar158@gmail.com

1 5. Duplicate objects are not allowed.


2 6. Insertion order is not preserved but all objects will be
3 inserted according to some priority.
4 7. Null is not allowed even as the 1st element for empty
5 PriorityQueue.Otherwise we will get the
6 "NullPointerException".
7 Constructors:
8 1. PriorityQueue q=new PriorityQueue();
9 Creates an empty PriorityQueue with default initial
10 capacity 11 and default natural sorting order.
11 2. PriorityQueue q=new PriorityQueue(int
12 initialcapacity,Comparator c);
13 3. PriorityQueue q=new PriorityQueue(int
14 initialcapacity);
15 4. PriorityQueue q=new PriorityQueue(Collection c);
16 5. PriorityQueue q=new PriorityQueue(SortedSet s);
17 Example 1:
18 import java.util.*;
19 class PriorityQueueDemo
20 {
21 public static void main(String[] args)
22 {
23 PriorityQueue q=new PriorityQueue();
24 //System.out.println(q.peek());//null
25
26 //System.out.println(q.element());//NoSuchEle
27 mentException
28 for(int i=0;i<=10;i++)
29 {
30 q.offer(i);
31 }
32 System.out.println(q);//[0, 1, 2, 3, 4,
33 5, 6, 7, 8, 9, 10]

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

1 2. It provides several methods for navigation purposes.


2 Diagram:
3

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

1 Searching the elements of a List:


2 Collections class defines the following methods to search
3 the elements of a List.
4 public static int binarySearch(List l,Object obj);
5 • If the List is sorted according to default natural sorting
6 order then we have to use this method.
7 public static int binarySearch(List l,Object
8 obj,Comparator c);
9 • If the List is sorted according to Comparator then we
10 have to use this method.
11 Program 1: To search elements of List.
12 import java.util.*;
13 class CollectionsSearchDemo
14 {
15 public static void main(String[] args)
16 {
17 ArrayList l=new ArrayList();
18 l.add("Z");
19 l.add("A");
20 l.add("M");
21 l.add("K");
22 l.add("a");
23 System.out.println(l);//[Z, A, M, K, a]
24 Collections.sort(l);
25 System.out.println(l);//[A, K, M, Z, a]
26
27 System.out.println(Collections.binarySearch(l
28 ,"Z"));//3
29
30 System.out.println(Collections.binarySearch(l
31 ,"J"));//-2
32 }
33 }

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

1 • Successful search range is: 0 to n-1.


2 • Unsuccessful search results range is: -(n+1)to -1.
3 • Total result range is: -(n+1)to n-1.
4 Example:
5

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

1 • public static void sort(object[] o,Comparator c);


2 To sort the elements of object[] array according to
3 customized sorting order.
4 Note: We can sort object[] array either by default natural
5 sorting order (or) customized sorting order but we can sort
6 primitive arrays only by default natural sorting order.
7
8 Program: To sort elements of array.
9 import java.util.*;
10 class ArraySortDemo
11 {
12 public static void main(String[] args)
13 {
14 int[] a={10,5,20,11,6};
15 System.out.println("primitive array
16 before sorting");
17 for(int a1:a)
18 {
19 System.out.println(a1);
20 }
21 Arrays.sort(a);
22 System.out.println("primitive array
23 after sorting");
24 for(int a1: a)
25 {
26 System.out.println(a1);
27 }
28 String[] s={"A","Z","B"};
29 System.out.println("Object array before
30 sorting");
31 for(String s1: s)
32 {
33 System.out.println(s1);
34 }
35 Arrays.sort(s);
36 System.out.println("Object array after
37 sorting");

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 }

23 Searching the elements of array:


24 Arrays class defines the following methods to search
25 elements of array.
26 1. public static int binarySearch(primitive[] p,primitive
27 key);
28 2. public static int binarySearch(Object[] p, object key);
29 3. public static int binarySearch(Object[] p,Object
30 key,Comparator c);
31 All rules of Arrays class binarySearch() method are
32 exactly same as Collections class binarySearch() method.
33
34 Program: To search elements of array.
89
Karrasankar158@gmail.com

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 }

34 Converting array to List:


35 Arrays class defines the following method to view array as
36 List.
37 public static List asList (Object[] o);

90
Karrasankar158@gmail.com

1 • Strictly speaking we are not creating an independent


2 List object just we are viewing array in List form.
3 • By using List reference if we are performing any
4 change automatically these changes will be reflected
5 to array reference similarly by using array reference if
6 we are performing any change automatically these
7 changes will be reflected to the List reference.
8 • By using List reference if we are trying to perform
9 any operation which varies the size then we will get
10 runtime exception saying
11 UnsupportedOperationException.
12 • By using List reference if we are trying to insert
13 heterogeneous objects we will get runtime exception
14 saying ArrayStoreException.
15 Program: To view array in List form.
16 import java.util.*;
17 class ArraysAsListDemo
18 {
19 public static void main(String[] args)
20 {
21 String[] s={"A","Z","B"};
22 List l=Arrays.asList(s);
23 System.out.println(l);//[A, Z, B]
24 s[0]="K";
25 System.out.println(l);//[K, Z, B]
26 l.set(1,"L");
27 for(String s1: s)
28 System.out.println(s1);//K,L,B
29
30 //l.add("ashok");//UnsupportedOperationExcept
31 ion
32
33 //l.remove(2);//UnsupportedOperationException
34 //l.set(1,new
35 Integer(10));//ArrayStoreException

91
Karrasankar158@gmail.com

1 }
2 }
3 Diagram:
4

92

S-ar putea să vă placă și