Anda di halaman 1dari 42

Collections Framework

An Array is an indexed collection of fixed number of homogeneous data elements.

The main advantage of Arrays is we can represent multiple values by using single variable so that
readability of the code will be improved.

Limitations of Arrays
1. Arrays are fixed in size. i.e., once we creates an Array there is no chance of increasing or decreasing the size
based on our requirement. Due to this, to use Arrays concept compulsory we should know the size in advance
which may not possible always.
2. Array can hold only homogeneous data type elements.
Example

Student[] s = new Student[10000];


s[0] = new Student(); // Valid
s[1] = new Customer(); // Compile Time Error

Object[] a = new Object[10000];


a[0] = new Student(); // Valid
a[1] = new Object(); // Valid

3. Arrays concept is not implemented based on some standard data structure and hence, readymade method
support is not available. For every requirement we have to write the code explicitly which increases complexity
of programming.
To overcome above problems of Arrays we should go for Collections concept.
1. Collections are growable in nature. i.e., based on our requirement we can increase or decrease the size.
2. Collections can hold both homogeneous and heterogeneous elements.
3. Every Collection class is implemented based on some standard data structure hence, for every requirement
readymade method support is available. Being a programmer we are responsible to use those methods and we
are not responsible to implement those methods.
Differences b/w Arrays and Collections
Arrays Collections
Arrays are fixed in size i.e., once we creates an array Collections are growable in nature i.e., based on our
we can’t increase or decrease size based on our requirement we can increase or decrease the size.
requirement.
With respect to memory Arrays are not With respect to memory Collections are
recommended to use. recommended to use.
With respect to performance Arrays are With respect to performance Collections are not
recommended to use recommenced to use.
Arrays can hold only homogenous data type Collections can hold both homogenous and
elements heterogeneous elements
There is no underlined data structure for Arrays and Every Collection class is implemented based on some
hence, readymade method support is not available. standard data structure and hence, for every
For every requirement we have to write the code requirement readymade method support is available.
explicitly which increases complexity of Being a programmer we can use this methods directly
programming. and we are not responsible to implement those
methods.
Arrays can hold both Primitives and Objects Collections can hold only Object types
Collection - If we want to represent a group of individual object as a single entity then we should go for
Collection.
Collection Framework - It contains several Classes an Interfaces which can be used to represent a group
of individual objects as a single entity.

Java C++
Collection Container
Collection Framework STL (Standard Template Library)

9 Key interfaces of Collection Framework


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

Collection
 If we want to represent a group of individual objects as a single entity then we should go for Collection.
 Collection interface defines the most common methods which are applicable for any collection object.
 In general Collection interface is considered as root interface of Collection framework.
There is no concrete class which implements Collection interface directly.
Difference b/w Collection and Collections
Collection is an interface, if we want to represent a group of individual objects as a single entity then we
should go for Collection.
Collections is a Utility class present in java.util package to define several utility methods for Collection
objects (like Sorting, Searching etc.).
List
 It is the child interface of Collection.
 It we want to represent a group of individual objects as a single entity where duplicates are allowed and
insertion order must be preserved then we should go for List.
Collection (I) – v1.2

List (I) – v1.2

ArrayList – v1.2 LinkedList – v1.2 Vector – v1.0

Stack – v1.0

Legacy Classes
Note: In v1.2 Vector and Stack classes are re-engineered to implement List interface.
Set
 It is the child interface of Collection.
 If we want represent a group of individual objects as a single entity where duplicates are not allowed and
insertion order not required then we should go for Set.
Collection (I) – v1.2

Set (I) – v1.2

HashSet – v1.2

LinkedHashset – v1.4

SortedSet
 It is the child interface of Set.
 If we want to represent a group of individual objects as a single entity where duplicates are not allowed and all
objects should be inserted according to some sorting order then we should go for SortedSet.
NavigableSet
 It is the child interface of SortedSet.
 It contains several methods for navigation purposes.
Collection (I) – v1.2

Set (I) – v1.2

SortedSet (I) – v1.2

NavigableSet (I) – v1.6

TreeSet – v1.2

Differences b/w List and Set


List Set
Duplicates are allowed Duplicates are not allowed
Insertion order preserved Insertion order not preserved
Queue
 It is a child interface of Collection.
 If we want to represent a group of individual objects prior to processing then we should go for Queue.
 Usually Queue follows First in First out (FIFO) order but, based on our requirement we can implement our own
priority order also.
Ex: Before sending a mail all mail IDs we have to store in some data structure. In which order we added mail
IDs in the same order only mail should be delivered. For this requirement Queue is best choice.
Collection (I) – v1.2

Queue (I) – v1.2 Introduced in v1.5

PriorityQueue BlockingQueue

PriorityBlockingQueue LinkedBlockingQueue

Note: All the above interfaces (Collection, List, Set, SortedSet, NavigableSet and Queue) meant for representing a
group of individual objects. If we want to represent a group of objects as key value pairs then we should go for Map
Map
 Map is not child interface of Collection.
 If we want to represent a group of objects as key value pairs then we should go for Map.
 Both key and value are objects only.
 Duplicate keys are not allowed but values can be duplicated.
Map (I) – v1.2 Dictionary (AC)

HashMap – v1.2 WeakHashMap – v1.2 IdentityHashMap – v1.2 Hashtable

LinkedHashMap – v1.2 Properties


Legacy Classes - v1.0

SortedMap
 It is the child interface of Map.
 If we want to represent a group of key value pairs according to some sorting order of keys then we should go
for SortedMap.
 In SortedMap the sorting should be based on key but not based on value.
NavigableMap
 It is the child interface of SortedMap
 It defines several methods for navigation purposes.
Map (I) – v1.2

SortedMap (I) – v1.2

NavigableMap (I) – v1.6

TreeMap – v1.2
Overview of Collection Interfaces and it’s implemented Classes
Collection (I) – v1.2

List (I) – v1.2 Set (I) – v1.2 Queue (I) – v1.2 Introduced in v1.5

ArrayList – v1.2 LinkedList – v1.2 Vector – v1.0 HashSet – v1.2 SortedSet (I) – v1.2 PriorityQueue BlockingQueue

Stack – v1.0 LinkedHashset – v1.4 NavigableSet (I) – v1.6 PriorityBlockingQueue LinkedBlockingQueue

Legacy Classes
TreeSet – v1.2

Overview of Map Interface and It’s implemented Classes


Map (I) – v1.2 Dictionary (AC)

HashMap – v1.2 WeakHashMap – v1.2 IdentityHashMap – v1.2 SortedMap (I) – v1.2 Hashtable

LinkedHashMap – v1.2 NavigableMap (I) – v1.6 Properties

Legacy Classes - v1.0


TreeMap – v1.2

Sorting
 Comparable - Class
 Comparator - Interface
Cursors
 Enumeration
 Iterator
 ListIterator
Utility Classes
 Collections
 Arrays
Note: The following are legacy characters present in Collection Framework.
 Enumeration(I)
 Dictionary(AC)
 Vector(C)
 Stack(C)
 Hashtable(C)
 Properties(C)
Collection
If we want to represent a group of individual objects as a single entity then we should go for Collection.
Collection interface defines the most common methods which are applicable for any collection object.
boolean add(Object o);
boolean addAll(Collection c);
boolean remove(Object o);
boolean removeAll(Collection c);
boolean retainAll(Collection c); - To remove all methods except those present in c
void clear();
boolean contains(Object o);
boolean containsAll(Collection c);
boolean isEmpty();
int size();
Object[] toArray();
Iterator iterator();

Note: There is no concrete class which implements Collection interface directly.


List
 List is child interface of Collection.
 If we want represent a group of individual objects as a single entity where duplicates are allowed
and insertion order must be preserved then we should go for List.
 We can preserve insertion order via index and we can differentiate duplicate objects by using index
hence, index will play very important role in List.
List interface defines the following specific methods
void add(int index, Object o);
boolean addAll(int index, Collection c);
Object get(int index);
Object remove(int index);
Object set(int index, Object o); - To replace the elements present in specified index
with provided Object and returns old Object
int indexOf(Object o); - Returns index of the first occurrence of object o
int lastIndexOf(Object o); - Returns index of the last occurrence of object o
ListIterator listIterator();

ArrayList
 The underlined data structure is Resizable Array or Growable Array.
 Duplicate objects are allowed
 Insertion order is preserved.
 Heterogeneous objects are allowed (Except TreeSet and TreeMap everywhere Heterogeneous
objects are allowed).
 null Insertion is possible.
Constructors

ArrayList al = new ArrayList() - Creates an empty ArrayList object with default initial
capacity (10). Once ArrayList reaches it max capacity then a new ArrayList object will
be created with New Capacity = (Current Capacity * 3 / 2) + 1.

ArrayList al = new ArrayList(int initialCapacity) - Creates an empty ArrayList object


with specified initial capacity.

ArrayList al = new ArrayList(Collection c) - Creates an equivalent ArrayList object for


the given Collection

Example:
package practice.collec;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("A");
al.add(10);
al.add("B");
al.add(null);
System.out.println(al); // [A, 10, B, null]
al.remove(2);
System.out.println(al); // [A, 10, null]
al.add(2, "G");
al.add("S");
System.out.println(al); // [A, 10, G, null, S]
}
}

Usually we can use collections to hold and transfer objects from one location to another location. To
provide support for this requirement every Collection class by default implements Serializable and
Cloneable interfaces.
 ArrayList and Vector classes implements RandomAccess interface so that any random element we
can access with the same speed.
RandomAccess
RandomAccess interface present in java.util package and it doesn’t contain any methods. It is a Marker
interface, where required ability will be provided automatically by the JVM.
ArrayList l1 = new ArrayList();
LinkedList l2 = new LinkedList();
System.out.println(l1 instanceof Serializable); // true
System.out.println(l1 instanceof Cloneable); // true
System.out.println(l1 instanceof RandomAccess); // true
System.out.println(l2 instanceof RandomAccess); // false
Note:
 ArrayList is the best choice if our frequent operation is Retrival operation (Because of Arraylist implements
RandomAccess).
 ArrayList is the worst choice if our frequent operation is insetion or deletion in the midddle.
Differences b/w ArrayList and Vector
ArrayList Vector
Every method present in the ArrayList is non Every method present in the Vector is Synchronized
synchronized
At a time multiple threads are allowed to operate on At a time only one Thread is allowed to operate on
ArrayList object and hence, it is not Thread Safe Vector object and hence, it is Thread Safe
Relatively performance is high because threads are Relatively performance is low because threads are
not required to wait to operate on ArrayList object required to wait to operate on Vector Object
Introduced in v1.2 and it is non legacy Introduced in v1.0 and it is legacy
How to get Synchronized version of ArrayList Object
By default ArrayList is non synchronized but, we can get synchronized version of ArrayList object by
using synchronizedList() of Collections class.
public static List synchronizedList(List list);

Example
ArrayList l = new ArrayList(); // l is non-synchronized list
List list = Collections.synchronizedList(l); // List is Synchronized
Similarly we can get synchronized version of Set and Map objects by using the following methods of
Collections class.
public static Set synchronizedSet(Set s);
public static Map synchronizedMap(Map m);

LinkedList
 The underlined data structure is double Linked List
 Insertion order is preserved
 Duplicate objects are allowed
 Heterogeneous objects allowed
 null insertion is possible
 LinkedList implements Serializable and Cloneable interfaces but not RandomAccess
 LinkedList is the best choice if out frequent operation is insertion or deletion in the middle
 LinkedList is the worst choice if our frequent operation is retrieval operation
Constructors
LinkedList l = new LinkedList() – Creates an empty linked list object
LinkedList l1 = new LinkedList(Collection c) – Creates an equivalent for the given
collection

LinkedList class specific methods


Usually we can use LinkedList to develop Stacks and Queues. To provide support for this requirement
LinkedList class defines the following specific methods.
void addFirst(Object o)
void addLast(Object o)
Object getFirst()
Object getLast()
Object removeFirst()
Object removeLast()
Example
package practice.collec;
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("Gangadhar");
l.add(20);
l.add(null)
l.add("Gangadhar");
System.out.println(l); // [Gangadhar, 20, null, Gangadhar]
l.set(0, "Ankireddy");
System.out.println(l); // [Ankireddy, 20, null, Gangadhar]
l.add(0, "Sravan");
System.out.println(l); // [Sravan, Ankireddy, 20, null, Gangadhar]
l.removeLast();
System.out.println(l); // [Sravan, Ankireddy, 20, null]
l.addFirst("Reddy");
System.out.println(l); // [Reddy, Sravan, Ankireddy, 20, null]
}
}

Differences b/w ArrayList and LinkedList


ArrayList LinkedList
ArrayList is the best choice if our frequent operation LinkedList is the best choice if our frequent operation
is Retrieval operation is Insertion or Deletion in the middle
ArrayList is the worst choice if our frequent LinkedList is worst choice if our frequent operation is
operation is Insertion / Deletion in the middle. Retrieval operation
Because internally several shift operation are
performed
In ArrayList the elements will be stored in In LinkedList the elements won’t be stored in
consecutive memory locations and hence Retrieval consecutive memory locations and hence Retrieval
operation will become easy operation will become complex
Vector
 The underlined data structure is Resizable Array or Growable Array
 Insertion order is preserved
 Duplicates are allowed
 Heterogeneous objects are allowed
 null insertion is possible
 It implements Serializable, Clonable and RandomAccess interface
 Every method present in the Vector is synchronized and hence Vector object is Thread safe.
Constructors
Vector al = new Vector() - Creates an empty Vector object with default initial capacity
(10). Once Vector reaches its max capacity then a new Vector object will be created
with New Capacity = (Current Capacity * 2).

Vector al = new Vector(int initialCapacity) - Creates an empty Vector object with


specified initial capacity.

Vector al = new Vector(int initialCapacity, int incrementalCapacity)

Vector al = new Vector(Collection c) - Creates an equivalent Vector object for the


given Collection. This constructor meant for inter conversion between Collection
objects.

Vector Specific Methods


void add(Object o) - C – To add items
void add(int index, Object o) - L
void addElement(Object o) - V

remove(Object o) – C – To remove Items


removeElement(Object o) - V
remove(int index) - L
removeElementAt(int index) - V
clear() - C
removeAllElements() - V

Object get(int index) – L - To get elements


Object elementAt(int index) – V
Object firstElement() - V
Object lastElement() - V

int size() - To get the size of Vector


int capacity() - To get the capacity of Vector
Enumeration elements() – To get the entire list of Vector
Example
package practice.collec;
import java.util.Vector;
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
System.out.println(v.capacity()); // 10
for (int i = 1; i <= 10; i++) {
v.addElement(i); // i is primitive Internally Auto boxing performed
}
System.out.println(v.capacity()); // 10
v.addElement('A'); // If we are trying to add new element capacity will
be New Capacity = (Old capacity * 2)
System.out.println(v.capacity()); // 20
System.out.println(v); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, A]
}
}

Stack
 It is the child class of Vector
 It is a specially designed class for Last in First out (LIFO) order.
Constructor
Stack s = new Stack(); // Default constructor

Stack Specific Methods


Object push(Object o) – To insert an object into the stack
Object pop() – To remove and return top of the stack
Object peek() – To return top of the stack without removal
boolean empty() – Returns true if the stack is empty
int search(Object o) – Returns offset if the element is available otherwise returns -1

Example
package practice.collec;
import java.util.Stack;
public class StackDemo {
public static void main(String[] args) {
Stack s = new Stack();
s.push("A");
s.push("G");
s.push("R");
System.out.println(s); // [A, G, R]
System.out.println(s.search("A")); // 3
System.out.println(s.search("S")); // -1
}
}
3 Cursors of Java
If we want to get Objects one by one from the Collection then we should go for Cursor. There are three
types of cursors available in Java.
1) Enumeration
2) Iterator
3) ListIterator
Enumeration
We can use Enumeration to get objects one by one from legacy collection object.
We can created Enumeration object by using elements() of Vector class.
public Enumeration elements()
Example
Enumeration e = v.elememts(); // v – Vector Object

Methods
public boolean hasMoreElements();
public Object nextElement();

Example
package practice.collec;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector v = new Vector();
for (int i = 0; i <= 10; i++) {
v.addElement(i);
}
System.out.println(v); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enumeration e = v.elements();
while (e.hasMoreElements()) {
Integer I = (Integer) e.nextElement();
if (I % 2 == 0) {
System.out.println(I); // 0 2 4 6 10
}
}
System.out.println(v); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}

Limitations of Enumeration ( v1.0 )


 We can apply Enumeration concept only for legacy classes and it is not a universal cursor.
 By using Enumeration we can get only read access and we can’t perform remove operation.
To overcome above limitations we should go for Iterator.
Iterator (I)
 We can apply Iterator concept for any collection object and hence it is universal cursor.
 By using Iterator we can perform both read and remove operations.
 We can create Iterator object by using iterator() of Collection interface.
public Iterator iterator();
Example
Iterator i = c. iterator(); // c – Any collection Object

Methods
public boolean hasNext();
public Object next();
public void remove();

Example
package practice.collec;
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList();
for (int i = 0; i <= 10; i++) {
al.add(i);
}
System.out.println(al); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator itr = al.iterator();
while (itr.hasNext()) {
Integer I = (Integer) itr.next();
if (I % 2 == 0) {
System.out.println(I); // 0 2 4 6 8 10
} else {
itr.remove();
}
}
System.out.println(al); // [0, 2, 4, 6, 8, 10]
}
}

Limitations of Iterator
 By using Enumeration and Iterator we can always move only towards forward direction and we can’t
move towards backward direction. These are single direction cursors but not bi-directional cursor.
 By using Iterator we can perform only read and remove operations and we can’t perform
replacement and addition of new object.
To overcome above limitations we should go for ListIterator.
ListIterator
 By using ListIterator we can move either to the forward direction or to the backward direction and
hence it is bi-directional cursor.
 By using ListIterator we can perform replacement and addition of new objects in addition to read
and remove operations.
 We can create ListIterator by using listIterator() of List interface.
public ListIterator listIterator();
Example
ListIterator ltr = l.listIterator(); // l – Any List Object
 ListIterator is the child interface of Iterator and hence all method present in Iterator by default
available to the ListIterator.
Methods
ListIterator defines the following 9 methods.
public boolean hasNext(); // Forward Direction
public Object next();
public int nextIndex();
public boolean hasPrevious(); // Previous Direction
public Object previous();
public int previousIndex();
public void remove(); // Extra Operations
public void add(Object o);
public void set(Object o);

Example
package practice.collec;
import java.util.LinkedList;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("BalaKrishna");
l.add("Venki");
l.add("Chiru");
l.add("Nag");
System.out.println(l); // [BalaKrishna, Venki, Chiru, Nag]
ListIterator ltr = l.listIterator();
while (ltr.hasNext()) {
String s = (String) ltr.next();
if (s.equals("Venki")) {
ltr.remove();
} else if (s.equals("Nag")) {
ltr.add("Chaithu");
} else if (s.equals("Chiru")) {
ltr.set("Charan");
}
}
System.out.println(l); // [BalaKrishna, Charan, Nag, Chaithu]
}
}
Note: The most powerful cursor is ListIterator but it’s limitation is, It is applicable only for List Objects
Comparison table of 3 Cursors
Property Enumeration Iterator ListIterator
Where we can apply? Only for Legacy Classes Any collection object Only for List objects
Is it Legacy? Yes (v1.0) No (v1.2) No (v1.2)
Movement Single Direction (Forward) Single Direction (Forward) Bi-Directional
Allowed Operations Only Read Read / Remove Read / Remove / Replace
/ Add
How we can get? By using elements() of By using iterator() of By using listIterator() of
Vector Class Collection Interface List Interface
Methods 2 Methods 3 Methods 9 Methods
 hasElements()  hasNext()  hasNext()
 nextElements()  next()  next()
 remove()  nextIndex()
 hasPrevious()
 previous()
 previousNext()
 remove()
 add(Object e)
 set(Object e)
Internal implementation of Cursors
Example
package practice.collec;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Vector;
public class CursorsDemo {
public static void main(String[] args) {
Vector v = new Vector();
Enumeration e = v.elements();
Iterator itr = v.iterator();
ListIterator ltr = v.listIterator();
System.out.println(e.getClass().getName()); // java.util.Vector$1
// Enumeration is anonymous inner class in Vector –
1 Means Anonymous inner class
System.out.println(itr.getClass().getName()); // java.util.Vector$Itr
// Iterator is implemented in Itr in Vector as inner class
System.out.println(ltr.getClass().getName()); // java.util.Vector$ListItr
// ListIterator is implemented in ListItr in Vector as inner class
}
}

Set
 Set is child Interface of Collection
 If we want to represent a group of individual objects as a single entity where duplicates are not
allowed and insertion order not preserved.
 Set Interface doesn’t contain any new method and we have to use only Collection Interface
methods.
HashSet
 The underlined data structure is HashTable
 Duplicate Objects are not allowed
 Insertion order is not preserved and it is based on hash code of Objects
 null insertion is possible (Only once)
 Heterogeneous objects are allowed
 Implements Serializable and Cloneable but not RandomAccess Interface
 HashSet is the best choice if our frequent operation is Search Operation
Note: In HashSet duplicates are not allowed if we are trying to insert duplicates then we won’t get any compile time
or Runtime errors and add method simply returns false.
Example
HashSet hs = new HashSet();
System.out.println(hs.add('A')); // true
System.out.println(hs.add('A')); // false | A is Duplicate It won’t inserted

Constructors
HashSet hs = new HashSet() - Creates an empty HashSet object with default initial
capacity (16) and default Fill Ratio / Load factor (0.75)
HashSet hs = new HashSet(int initialCapacity) – Creates an empty HashSet object with
specified initial capacity and default Fill ratio / Load factor (0.75)
HashSet hs = new HashSet(int initialCapacity, float loadFactor) - Creates an empty
HashSet object with specified initial capacity and specified Fill ratio / Load factor.
HashSet hs = new HashSet(Collection c) – Creates an Equivalent HashSet for the given
Collection. This constructor meant for Inter conversion between Collection objects.

Fill Ratio / Load Factor


After filling how much ratio a new HashSet object will be created, this ratio is called Fill Ratio / Load
Factor. Default Fill ratio / Load factor is 0.75.
Ex: Fill Ratio 0.75 means after filling 75% ratio a new HashSet object will be created automatically.
Example
package practice.collec;
import java.util.HashSet;
public class HashSetDemo {
public static void main(String[] args) {
HashSet hs = new HashSet();
hs.add("B");
hs.add("C");
hs.add("D");
hs.add("Z");
hs.add(null);
hs.add(10);
System.out.println(hs.add("Z")); // false
System.out.println(hs); // [null, D, B, C, 10, Z] |
Insertion order not preserved it may change
}
}

LinkedHashSet
 It is the child class of HashSet
 It is exactly same as Hashset(Including Constructors and Methods) except the following differences.
HashSet LinkedHashSet
The underlying data structure is HashTable The underlying data structure is a combination of
LinkedList and HashTable
Insertion order not preserved Insertion order preserved.
Introduced in v1.2 Introduced in v1.4
 In the above program if we replace HashSet with LinkedHashSet then the output is as below.
[B, C, D, Z, null, 10] | Now insertion order is preserved
Note: In general, we can LinkedHashSet to develop cache based applications where duplicates are not allowed and
Insertion order is preserved.
SortedSet
 SortedSet Interface is the child Interface of Set
 If we want to represent a group of individual objects according to some sorting order without
duplicates then we should go for SortedSet
 SortedSet interface defines the following specific methods
Object first(); - Returns First element of the SortedSet
Object last(); - Returns Last element of the SortedSet
SortedSet headSet(Object obj); - Returns SortedSet whose elements are less than obj
SortedSet tailSet(Object obj); - Returns SortedSet whose elements are Greater than (>=)
obj
SortedSet subSet(Object obj1, Object obj2); - Returns SortedSet whose elements are
Greater than are equals(>=) obj1 and less than (<) obj2.
Comparator comparator(); - Returns Comparator object that describes underlying sorting
technique. If we are using default natural sorting order then we will get null
Note: The default natural sorting order for Numbers Ascending Order and for String objects Alphabetical Order.

SortedSet contains elements [100, 101, 104, 106, 110, 115, 120]
Object first(); | 100
Object last(); | 120
SortedSet headSet(106); | [100, 101, 104]
SortedSet tailSet(Object obj); | [106, 110, 115, 120]
SortedSet subSet(Object obj1, Object obj2); | [101, 104, 106, 110]
Comparator comparator(); | null – As it is default sorting Order

TreeSet
 The underlying data structure is Balanced Tree
 Duplicate objects are not allowed
 Insertion order not preserved
 Heterogeneous objects are not allowed otherwise we will get Runtime Exception saying
ClassCastException
 null insertion is possible(Only once)
 TreeSet Implements Serializable and Cloneable interfaces but not RandomAccess
 All objects will be inserted based on Some Sorting order it may be default natural sorting order or
customized sorting order
Constructors
TreeSet ts = new TreeSet()- Creates an empty TreeSet object where the elements will be
inserted according to default natural order.
TreeSet ts = mew TreeSet(Comparator c) – Creates an empty TreeSet object where the
elements will be inserted according to customized sorting order specified by Comparator
object
TreeSet ts = mew TreeSet(Collection c) – Creates an Equivalent TreeSet for the given
Collection where the elements will be inserted according to default sorting order. This
constructor meant for Inter conversion between Collection objects.
TreeSet ts = mew TreeSet(SortedSet s) – Creates an Equivalent TreeSet for the given
SortedSet object.

Example1
package practice.collec;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add("A");
ts.add("a");
ts.add("B");
ts.add("Z");
ts.add("L");
System.out.println(ts); // [A, B, L, Z, a]
ts.add(new Integer(10)); // RE: ClassCastException
ts.add(null); // RE: NullPointerException
}
}
null acceptance
 For non-empty TreeSet if we are trying insert null then we will get NullPointerException.
 For empty TreeSet as the first element null is allowed but, after inserting that null, if we are trying to
insert any other then we will get Runtime Exception saying NullPointerException.
Note: Until v1.6 null is allowed as the first element to the empty TreeSet but, v1.7 onwards null is not allowed even
as the first element. i.e., ‘null’ such of story not applicable for TreeSet from v1.7 onwards.
Example2
package practice.collec;
import java.util.TreeSet;
public class TreeSetDemo2 {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new StringBuffer("A"));
ts.add(new StringBuffer("Z"));
ts.add(new StringBuffer("L"));
ts.add(new StringBuffer("B"));
System.out.println(ts); // RE: ClassCastException
}
}
 If we are depending on default natural sorting order compulsory the objects should be homogenous
and comparable. Otherwise we will get Runtime Exception saying ClassCastException.
 An object is said to be comparable if and only if corresponding class implements comparable
interface. String Class and all Wrapper classes already implements Comparable interface but,
StringBuffer class doesn’t implement Comparable interface. Hence, we got ClassCastException in the
above Example.
Comparable
 It is present in java.lang package and it contains only one method (compareTo())
obj1.compareTo(Object obj2);
 Returns –ve iff obj1 has to come before obj2
 Returns +ve iff obj1 has to come after obj2
 Returns 0 iff obj1 and obj2 are equal
Example
package practice.collec;
public class CompareToDemo {
public static void main(String[] args) {
System.out.println("A".compareTo("Z")); // -25(-ve)
System.out.println("Z".compareTo("A")); // 25(+ve)
System.out.println("A".compareTo("A")); // 0
System.out.println("A".compareTo(null)); // RE: NullPointerException
}
}

 If we are depending on default natural sorting order then while adding objects into the TreeSet JVM
will call compareTo()
Example
TreeSet t = new TreeSet();
t.add("G");
t.add("A"); // “A”.compartTo(“G”)
t.add("R"); // “R”.compartTo(“G”)
t.add("A"); // “A”.compartTo(“G”) | “A”.compartTo(“A”)
System.out.println(t); // [A, G, R]
Note: If default natural sorting order not available or if we are not satisfied with default natural sorting order then
we can go for customized sorting by using Comparator.
 Comparable meant for default natural sorting order
 Comparator meant for Customized sorting order
Comparator
 Comparator present in java.util package and it defines two methods compare() and equals()
public int compare(Object obj1, Object obj2);
 Returns –ve iff obj1 has to come before obj2
 Returns +ve iff obj1 has to come after obj2
 Returns 0 iff obj1 and obj2 are equal
public boolean equals(Object obj);

 Whenever we are implementing Comparator Interface compulsory we should provide


implementation only for compare() and we are not required provide implementation for equals()
because it is already available to our class from Object class through Inheritance.
Write a program to insert Integer objects into the TreeSet where the sorting order is descending order?
package practice.collec;
import java.util.Comparator;
import java.util.TreeSet;
public class ComparatorDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator()); //
 If we are not passing Comparator object then internally JVM will call
compareTo() which is meant for default natural sorting order(Ascending Order).
In this case the output is [0, 5, 10, 15, 20]
 If we are passing Comparator object then JVM will call compare() which is meant
for customized sorting order. In this case the output is [20, 15, 10, 5, 0]
t.add(10);
t.add(0); // compare(0,10)
t.add(15); // compare(15,10)
t.add(5); // compare(5,10), compare(5,0)
t.add(20); // compare(20,10), compare(20,15)
t.add(20); // compare(20,10), compare(20,15), compare(20,20)
System.out.println(t); // [20, 15, 10, 5, 0]
}
}
class MyComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
Integer I1 = (Integer) obj1;
Integer I2 = (Integer) obj2;
if (I1 < I2) {
return +1;
} else if (I1 > I2) {
return -1;
} else {
return 0;
}
}
}

Various possible implementations of compare()


class MyComparator2 implements Comparator {
public int compare(Object obj1, Object obj2) {
Integer I1 = (Integer) obj1;
Integer I2 = (Integer) obj2;
1. return I1.compareTo(I2); // Default natural Sorting order(Ascending Order)
[0, 5, 10, 15, 20]
2. return -I1.compareTo(I2); // Descending Order [20, 15, 10, 5, 0]
3. return I2.compareTo(I1); // Descending Order [20, 15, 10, 5, 0]
4. return -I2.compareTo(I1); // Ascending Order [0, 5, 10, 15, 20]
5. return +1; // Insertion order [10, 0, 15, 5, 20, 20]
6. return -1; // Reverse of insertion order [20, 20, 5, 15, 0, 10]
7. return 0; // Only first element will be inserted and all remaining as
considered as duplicated [10]
}
}
Write a program to insert String objects into the TreeSet where all elements should be inserted
according reverse of Alphabetical order?
package practice.collec;
import java.util.Comparator;
import java.util.TreeSet;
public class ComparatorStringDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator2());
t.add("Roja");
t.add("Shobha Rani");
t.add("Raja Kumari");
t.add("Ganga Bhavani");
t.add("Ramulamma");
System.out.println(t); // [Shobha Rani, Roja, Ramulamma, Raja Kumari,
Ganga Bhavani]
}
}
class MyComparator2 implements Comparator{
public int compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = obj2.toString();
//return -s1.compareTo(s2);
return s2.compareTo(s1);
}
}

Write a program to insert StrngBuffer objects into the TreeSet where sorting order is Alphabetical
order?
package practice.collec;
import java.util.Comparator;
import java.util.TreeSet;
public class ComparatorStrBufDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator3());
t.add(new StringBuffer("A"));
t.add(new StringBuffer("Z"));
t.add(new StringBuffer("K"));
t.add(new StringBuffer("L"));
System.out.println(t); // [A, K, L, Z]
}
}
class MyComparator3 implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s1.compareTo(s2);
}
}
Note:
 If we are depending on default natural sorting order compulsory the objects should be homogenous and
comparable otherwise we will get Runtime Exception saying ClassCaseException.
 If we are defing our own sorting by Comparator then objects need not be comparable and homogenous i.e., we
can add hetrogenous non comparable objects also.
Write a program to insert String and StringBuffer objects into TreeSet where sorting order is increasing
length order, if two objects having same length then consider their Alphabetical Order?
package practice.collec;
import java.util.Comparator;
import java.util.TreeSet;
public class ComparatorStrStrBufDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet(new MyComparator4());
t.add("A");
t.add(new StringBuffer("ABC"));
t.add(new StringBuffer("AA"));
t.add("XX");
t.add("ABCD");
t.add("A");
System.out.println(t); // [A, AA, XX, ABC, ABCD]
}
}
class MyComparator4 implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
int i1 = s1.length();
int i2 = s2.length();
if (i1 < i2) {
return -1;
} else if (i1 > i2) {
return +1;
} else {
return s1.compareTo(s2); // [A, AA, XX, ABC, ABCD]
// return 0; // [A, AA, ABC, ABCD] duplicate length is not considered
}
}
}

Comparable Vs Comparator
 For Pre-Defined Comparable classes(Like String..) default natural sorting order already available, if
we are not satisfied with default natural sorting order then we can define our own sorting by using
Comparator
 For Pre-Defined non Comparable classes(Like StringBuffer) default natural sorting order not already
available, we can define our own sorting by using Comparator
 For User defined classes (Like Employee...),
o The person who is writing the class is responsible to define default natural sorting order by
implementing Comparable Interface.
o The person who is using our class, if he is not satisfied with default natural sorting order then he
can define his own sorting by using Comparator.
Pre-defined Pre-defined Our Own
Comparable Non-Comparable Implemented
Classes Classes Classes

String StringBuffer Employee

The Person The Person


Who is writing Who is Using
The class The class

Comparable Comparator Comparable Comparable


Default Natural Sorting Order Customized Sorting Order

Example – ComparableComparatorDemo.java
package practice.collec;
import java.util.Comparator;
import java.util.TreeSet;
class Employee implements Comparable {
String name;
int eno;
Employee(String name, int eno) {
this.name = name;
this.eno = eno;
}
public String toString() {
return name + "-" + eno;
}
public int compareTo(Object o) {
int eno1 = this.eno;
Employee e = (Employee) o;
int eno2 = e.eno;
if (eno1 < eno2)
return -1;
else if (eno1 > eno2)
return 1;
else
return 0;
}
}
class MyComparator5 implements Comparator {
public int compare(Object o1, Object o2) {
Employee e1 = (Employee) o1;
Employee e2 = (Employee) o2;
String s1 = e1.name;
String s2 = e2.name;
return s1.compareTo(s2);
}
}

(Cond…)
(Cond…)
public class ComparableComparatorDemo {
public static void main(String[] args) {
Employee e1 = new Employee("Nag", 100);
Employee e2 = new Employee("Balaiah", 200);
Employee e3 = new Employee("Chiru", 50);
Employee e4 = new Employee("Venki", 150);
Employee e5 = new Employee("Nag", 100);
TreeSet t1 = new TreeSet();
t1.add(e1);
t1.add(e2);
t1.add(e3);
t1.add(e4);
t1.add(e5);
System.out.println(t1); // [Chiru-50, Nag-100, Venki-150, Balaiah-200]
TreeSet t2 = new TreeSet(new MyComparator5());
t2.add(e1);
t2.add(e2);
t2.add(e3);
t2.add(e4);
t2.add(e5);
System.out.println(t2); // [Balaiah-200, Chiru-50, Nag-100, Venki-150]
}
}

Comparison of Comparable and Comparator


Comparable Comparator
It is meant for Default Natural Sorting Order It is meant for Customized Soring order
Present in java.lang package Present in java.util package
It defines only one Method It defines two methods
 compareTo()  compare()
 equals()
String and all Wrapper classes implements The only implemented classes of Comparator are
Comparable Interface  Collator
 RuleBasedCollator – Used in GUI based Applications
Comparison table set implemented classes
Property HashSet LinkedHashSet TreeSet
Underlying Data structure HashTable A combination Linked Balanced Tree
list and HashTable
Duplicate Objects Not Allowed Not Allowed Not Allowed
Insertion Order Not Preserved Preserved Not Preserved
Sorting Order NA NA Applicable
Heterogeneous Objects Allowed Allowed Not Allowed
null Acceptance Allowed Allowed For Empty TreeSet as first
element null is allowed
Note: For Empty TreeSet as the first element null is allowed but, this rule is applicable until v1.6 only. From v1.7
onwards null is not allowed even as the first element
Map
 Map is not child Interface of Collection
 If we want to represent a group of objects as key-value pairs then we should go for Map
 Both keys and values are objects only
 Duplicates keys are not allowed but values can be duplicated
 Each key-value pair is called Entry hence, Map is considered as a collection of Entry objects
Map Interface Methods
Object put(Object key, Object value); - To add one key value pair to the Map. If the
key is already present then old value will be replaced with new value and returns old
value
Example
m.put(101,"Ganga"); // null
m.put(102,"Sravs"); // null
m.put(103,"Murali"); // Ganga

void putAll(Map m);


Object get(Object key); - returns the value associated with specified key
Object remove(Object key); - Removes the entry associated with specified key
boolean containsKey(Object key);
boolean containsValue(Object value);
boolean isEmpty();
int size();
int size(); - Clears all key and value pairs
Set keySet(); - To get all Keys available in Map and it returns Set
Collection values(); - To get all Values available in Map and it returns Collection
Set entrySet(); - To get Entries of Map and it returns Set

Entry(I)
 A Map is a group of key-value pairs and each key-value pair called an Entry. Hence, a Map is
considered as a Collection of Entry objects.
 Without existing Map object there is no chance of existing Entry object. Hence, entry interface is
defined inside Map interface
interface Map {
interface Entry {
Object getKey();
Object getValue();
Object setValue(Object value); // Entry specific methods and we can apply
on only on Entry object
}
}

HashMap
 The underlying data structure is Hashtable
 Insertion order is not preserved and it is based on hash code of Keys
 Duplicate keys are not allowed but values can be duplicated
 Heterogeneous objects are allowed for both key and value
 null is allowed for key (only once)
 null is allowed for values(any number of types)
 HashMap implements Serializable and Cloneable interfaces but not RandomAccess
 HashMap is the best choice if our frequent operation is Search Operation
Constructors
HashMap hs = new HashMap() - Creates an empty HashMap object with default initial
capacity (16) and default Fill Ratio / Load factor (0.75)
HashMap hs = new HashMap(int initialCapacity) – Creates an empty HashMap object with
specified initial capacity and default Fill ratio / Load factor (0.75)
HashMap hs = new HashMap(int initialCapacity, float loadFactor) - Creates an empty
HashMap object with specified initial capacity and specified Fill ratio / Load factor.
HashMap hs = new HashMap(Map m) – Creates an Equivalent HashMap for the given Map.

Example
package practice.map;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapDemo {
public static void main(String[] args) {
HashMap m = new HashMap();
m.put("Chiranjeevi", 700);
m.put("Balaiah", 800);
m.put("Venkatesh", 200);
m.put("Nagarjuna", 500);
System.out.println(m);
// {Venkatesh=200, Chiranjeevi=700, Nagarajuna=500, Balaiah=800}
System.out.println(m.put("Chiranjeevi", 1000)); // 700
Set s = m.keySet();
System.out.println(s); // [Venkatesh, Chiranjeevi, Nagarajuna, Balaiah]
Collection c = m.values();
System.out.println(c); // [200, 1000, 500, 800]
Set s1 = m.entrySet();
System.out.println(s1);
// [Venkatesh=200, Chiranjeevi=1000, Nagarajuna=500, Balaiah=800]
Iterator itr = s1.iterator();
while (itr.hasNext()) {
Map.Entry m1 = (Map.Entry) itr.next();
System.out.println(m1.getKey() + "--" + m1.getValue()+" ");
// Venkatesh--200 Chiranjeevi--1000 Nagarajuna--500 Balaiah--800
if (m1.getKey().equals("Nagarjuna")) {
m1.setValue(10000);
}
}
System.out.println(m);
// {Venkatesh=200, Chiranjeevi=1000, Nagarjuna=10000, Balaiah=800}
}
}
Differenced b/w HashMap and Hashtable
HashMap Hashtable
Every method present in HashMap is Non – Every method present in Hashtable is Synchronized
Synchronized
At a multiple Threads are allowed to operate on At a time only one Thread is allowed to operate on
HashMap object and hence it is not Thread safe Hashtable and hence it is Thread safe
Relatively performance is High because, Threads are Relatively performance is Low because, Threads are
not required to wait to operate on HashMap object required to wait to operate on Hashtable object
null is allowed for both Key and Value null is not allowed for Keys and Values. Otherwise we
will get NullPointerException
Introduced in v1.2 and it is not legacy Introduced in v1.0 and it is legacy
How to get Synchronized version of HashMap Object?
By default HashMap is Non-Synchronized but we can get Synchronized version of HashMap by using
synchronizedMap() of Collections class.
public static Map synchronizedMap(Map map);

Example
Hashmap m = new HashMap(); // m is non-synchronized Map
Map map = Collections.synchronizedMap(m); // Map is Synchronized

LInkedHashMap
 It is the child class of HashMap
 It is exactly same as HashMap(including methods and constructors) except the following differences
HashMap LinkedHashMap
The underlying data structure is Hashtable The underlying data structure is a combination of
LinkedList and Hashtable (Hybrid data structure)
Insertion order is not preserved and it is based on Insertion order is preserved
hash code of Keys
Introduced in v1.2 Introduced in v1.4
 In the above HashMap example if we replace HashMap with LinkedHashMap then output is
{Chiranjeevi=1000, Balaiah=800, Venkatesh=200, Nagarjuna=10000}

that is insertion order is preserved.


Note: LinkedHashSet and LinkedHashMap are commonly used for developing cache based applications.
Difference b/w == operator and equals() – In general == operator meant for reference comparison
(Address comparison) whereas equals() meant for content comparison.
IdentityHashMap
 It is exactly same as HashMap(Including Methods and Constructors) except the following difference
o In the case normal HashMap JVM will use equals() to identify duplicate Keys, which is meant
for content comparison
o In the case of IdentityHashMap JVM will use == operator to identity duplicate Keys, which is
meant for reference comparison (Address Comparison)
Example
HashMap m = new HashMap();
Integer I1 = new Integer(10);
Integer I2 = new Integer(10);
m.put(I1, "Gangadhar");
m.put(I2, "Ankireddy");
System.out.println(m); // {10=Ankireddy}

I1 and I2 are duplicate keys because I1.equals(I2) returns true


If we replace HashMap with IdentityHashMap then I1 and I2 are not duplicate keys
because I1 == I2 returns false. In this case output is {10=Gangadhar, 10=Ankireddy}

WeakHashMap
 It is exactly same as HashMap except the following difference
o In the case HashMap even though object doesn’t have any reference it is not eligible for gc if
it is associated with HashMap. i.e., HashMap dominates Garbage collector
o In the case of WeakHashMap, if object doesn’t contain any references it is eligible for gc
even though object associated with WeakHashMap. i.e., Garbage Collector dominates
WeakHashMap
Example
package practice.map;
import java.util.HashMap;
public class WeakHashMapDemo {
public static void main(String[] args) throws Exception {
HashMap m = new HashMap();
Temp t = new Temp();
m.put(t, "Gangadhar");
System.out.println(m);
t = null;
System.gc();
Thread.sleep(5000);
System.out.println(m);
}
}
class Temp {
public String toString() {
return "temp";
}
public void finalize() {
System.out.println("Finalize Method in Temp");
}
}
In the above example temp object not eligible for gc because it is associate with
HashMap. In this case Output is
{temp=Gangadhar}
{temp=Gangadhar}

In the above program if we replace HashMap with WeakHashMap then temp object eligible
for gc. In this case Output is
{temp=Gangadhar}
Finalize Method in Temp
{}
SortedMap(I)
 It is the child interface of Map
 If we ant to represent a group of key-value pairs according to some sorting order of keys then we
should go SortedMap
 Sorting is based on the Key but not based on Value
 SortedMap defines the following specific methods
Object firstKey(); - Returns First Key of the SortedMap
Object lastKey(); - Returns Last Key of the SortedMap
SortedMap headMap(Object key); - Returns SortedMap whose Entry are less than key
SortedMap tailMap(Object key); - Returns SortedMap whose Entry are Greater than (>=)
key
SortedMap subMap(Object key1, Object key2); - Returns SortedSet whose Entry are Greater
than are equals(>=) key1 and less than (<) key2.
Comparator comparator(); - Returns Comparator object that describes underlying sorting
technique. If we are using default natural sorting order then we will get null

SortedMap contains Entrys {100=A, 101=B, 104=C, 106=D, 110=E, 115=F, 120=G}
Object firstKey(); | 100
Object lastKey(); | 120
SortedMap headMap(106); | {100=A, 101=B, 104=C}
SortedMap tailMap(Object obj); | {106=D, 110=E, 115=F, 120=G}
SortedMap subMap(Object obj1, Object obj2); | {101=B, 104=C, 106=D, 110=E}
Comparator comparator(); | null – As it is default sorting Order

TreeMap
 The underlying data structure RED-BLACK tree
 Insertion order is not preserved and it based on some sorting order or Keys
 Duplicate keys are not allowed but values can be duplicated
 If we are depending on Default Natural Sorting Order then Keys should be Homogenous and
Comparable Otherwise we will get runtime exception saying ClassCastException
 If we are defining our own sorting order by Comparator then keys need not be Homogenous and
Comparable, we can take Heterogenous and non-comparable objects also.
 Whether we are depending on default natural sorting order or customized sorting order there are
no restrictions for values, we can take heterogenous non-comparable objects also.
null acceptance
 For non-empty TreeMap, if we trying to insert an entry with null key then we will get Runtime
exceptions saying NullPointerException.
 For empty TreeMap as the first entry with null key is allowed but, after inserting that entry if we are
trying insert any other entry then we will get runtime exception saying NullPointerException
Note: The above null acceptance rule applicable until v.1.6 only, from v1.7 onwards null is not allowed for Key. But
for Values we can use null any number of times, there is no restriction whether it is v1.6 or v1.7.
Constructors
TreeMap tm = new TreeMap()- Creates an empty TreeMap object where the elements will be
inserted according to default natural order.
TreeMap tm = new TreeMap(Comparator c) – Creates an empty TreeMap object where the
elements will be inserted according to customized sorting order specified by Comparator
object
TreeMap tm = new TreeMap(Collection c) – Creates an Equivalent TreeMap for the given
Collection where the elements will be inserted according to default sorting order. This
constructor meant for Inter conversion between Collection objects.
TreeMap tm = new TreeMap(SortedMap s) – Creates an Equivalent TreeMap for the given
SortedMap object.

Example – Default Natural Sorting Order


package practice.map;
import java.util.TreeMap;
public class TreeMapDemo {
public static void main(String[] args) {
TreeMap m = new TreeMap();
m.put(101, "AAA");
m.put(102, "BBB");
m.put(103, "CC");
m.put(104, 105);
System.out.println(m); // {101=AAA, 102=BBB, 103=CC, 104=105}
m.put("DDD", "EEE"); // RE: ClassCastException
m.put(null, "FFF"); // RE: NullPointerException
}
}

Example – Customized Sorting Order


package practice.map;
import java.util.Comparator;
import java.util.TreeMap;
public class TreeMapDemo2 {
public static void main(String[] args) {
TreeMap m = new TreeMap(new MyComparator());
m.put("XXX", 10);
m.put("AAA", 20);
m.put("ZZZ", 30);
m.put("LLL", 40);
System.out.println(m); // {ZZZ=30, XXX=10, LLL=40, AAA=20}
}
}
class MyComparator implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = o1.toString();
String s2 = o2.toString();
return s2.compareTo(s1);
}
}
Hashtable
 The underlying data structure for Hashtable is Hashtable
 Insertion order is not preserved and it is based on hash code of Keys
 Duplicate keys are not allowed but Values can be duplicated
 Heterogenous objects are allowed for both keys and values
 null is not allowed for both key and value. Otherwise we will get runtime exception saying
NullPointerException
 it implements Serializable and Cloneable interfaces but not RandomAccess
 Every method present in Hashtable is Synchronized and hence Hashtable object is Thread safe
 Hashtable is the best choice if our frequent operation is Search operation
Constructor
Hashtable ht = new Hashtable() - Creates an empty Hashtable object with default initial
capacity (11) and default Fill Ratio / Load factor (0.75)
Hashtable ht = new Hashtable(int initialCapacity) – Creates an empty Hashtable object
with specified initial capacity and default Fill ratio / Load factor (0.75)
Hashtable ht = new Hashtable(int initialCapacity, float loadFactor) - Creates an empty
Hashtable object with specified initial capacity and specified Fill ratio / Load
factor.
Hashtable ht = new Hashtable(Map m) – Creates an Equivalent Hashtable for the given
Map. Inter conversion between Map objects

Example
package practice.map;
import java.util.Hashtable;
public class HashtableDemo {
public static void main(String[] args) {
Hashtable h = new Hashtable();
h.put(new Temp2(5), "A");
h.put(new Temp2(2), "B");
h.put(new Temp2(6), "C");
h.put(new Temp2(15), "D");
h.put(new Temp2(23), "E");
h.put(new Temp2(16), "F");
System.out.println(h); // {6=C, 16=F, 5=A, 15=D, 2=B, 23=E} |
While Printing Hashtable From Top to Bottom and Right to Left
h.put(new Temp2(16), null); // RE: NullPointerException
}
}
class Temp2 {
int i;
Temp2(int i) {
this.i = i;
}
public int hashCode() {
return i;
}
public String toString() {
return i + "";
} }
If we change hashCode() of Temp2 class as
public int hashCode() {
return i % 9;
}
Then Output is: {16=F, 15=D, 6=C, 23=E, 5=A, 2=B}
--------------------------------------------------------------------------------------------------------------------------------

If we configure initial capacity as 25 i.e.,


Hashtable h = new Hashtable(25);
Then Output is: {23=E, 16=F, 15=D, 6=C, 5=A, 2=B}

Properties
In our program if anything which changes frequently (like, user name, password, mail id, mobile n…) are
not recommended to hardcode in Java program. Because if there is any change to reflect that change
recompilation, rebuild, redeploy application are required. Even sometimes server restart also required.
Which creates a big business impact to the client.
We can overcome this problem by using Properties file. Such type of variable things we have to
configure in the properties file. From the properties file we have to read into Java program and we can
use those properties. The main advantage of this approach is, if there is a change in properties file to
reflect that change just redeployment is enough which won’t create any business impact to the client.
We can use Java Properties object to hold properties which are coming from properties file.
In normal Map (like HashMap, Hashtable, TreeMap...) Key and Value can be any type. But, in the case of
Properties Key and Value should be String type.
Constructors
Properties p = new Properties () - Creates an empty Properties object

Methods
String setProperty(String key, String value) – To set a new property. If the specified
property already available then old value will be replaced with new value and returns
old value.
String getProperty(String key) – To get value associated with specified property. If
the specified property is not available then this method returns null
Enumeration propertyNames() – Returns all property name present in properties object
void load(InputStream inStream) – To load properties from properties file into Java
Properties object
void save(OutputStream out, String comments) – To Store properties from Java Properties
into Properties file

Example
test.properties
username=Gangadhar
password=ganga123
Ganga=9999
PropertiesDemo.java
package practice.map;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
FileInputStream fis = new FileInputStream("test.properties");
p.load(fis);
System.out.println(p); // {Ganga=8888, password=ganga123,
username=Gangadhar}
String s = p.getProperty("Ganga");
System.out.println(s); // 9999
p.setProperty("Sravs", "8888");
FileOutputStream fos = new FileOutputStream("test.properties");
p.store(fos, "Updated by Gangadhar for Demo");
}
}

test.properties - file after storing the data


#Updated by Gangadhar for Demo
#Thu Dec 07 18:29:35 IST 2017
Ganga=9999
password=ganga123
Sravs=8888
username=Gangadhar

Example – to create Connection object


package practice.map;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class PropertiesDemo2 {
public static void main(String[] args) throws Exception {
Properties p = new Properties();
FileInputStream fis = new FileInputStream("db.properties");
p.load(fis);
String url = p.getProperty("url");
String uname = p.getProperty("uname");
String password = p.getProperty("password");
Connection con = DriverManager.getConnection(url, uname, password);
}
}
v1.5 Enhancements
(Queue (I))
 It is the child interface of Collection
 If we want to represent a group of individual objects prior to processing then we should go for
Queue
Ex: Before sending SMS, all mobile numbers we have to store in some data structure. In which order
we added mobile numbers in the same order only message should be delivered. For this First in First
out requirement Queue is the best choice
 Usually Queue follows First in First out order but, based on our requirement we can implement our
own priority order also(Priority Queue)
 From v1.5 onwards LinkedList class also implements Queue Interface
 LinkedList based implementation of Queue always follows First in First out order
Queue Interface Specific Methods
boolean offer(Object e) – To add an object into the Queue
Object peek() – To return head element of the Queue. If Queue is empty then this method
returns null.
Object element() – To return head element of the Queue. If Queue is empty then this
method raises RE: NoSuchElementException
Object poll() – To remove and return head element of the Queue. If Queue id empty then
this method returns null.
Object remove() – To remove and return head element of the Queue. If Queue is empty
then this method raises RE: NoSuchElementException

PriorityQueue
 If we want represent a group of individual objects prior to processing according to some priority
then we should go for PriorityQueue
 The Priority can be either Default Natural Sorting Order or Customized Sorting Order defined by
Comparator
 Insertion order is not preserved and it is based on some priority
 Duplicate objects are not allowed
 If we are depending on Default Natural Sorting Order compulsory the objects should be
Homogenous and Comparable otherwise we will get runtime exception saying ClassCastException
 If we are defining our own sorting by Comparator then objects need not be Homogenous and
Comparable
 null is not allowed even as the first element also.
Constructors

PriorityQueue pq = new PriorityQueue() - Creates an empty PriorityQueue with default


initial capacity(11) and all objects will be inserted according to DNSO
PriorityQueue pq = new PriorityQueue(int initialCapacity) – Creates an empty
PriorityQueue with specified initial capacity and all objects will be inserted
according to Default Natural Sorting Order.
(Cont..)
(Cont..)
PriorityQueue pq = new PriorityQueue(int initialCapacity, Comparator c) - Creates an
empty PriorityQueue object with specified initial capacity and specified sorting order
by Comparator
PriorityQueue pq = new PriorityQueue(SortedSet s) – Creates an Equivalent PriorityQueue
for the given SortedSet.
PriorityQueue pq = new PriorityQueue(Collection c) – Creates an Equivalent
PriorityQueue for the given Collection. Inter conversion between Map objects

Example1
package practice.collec;
import java.util.PriorityQueue;
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();
System.out.println(pq.peek()); // null
System.out.println(pq.element()); // RE: NoSuchElementException
for (int i = 0; i <= 10; i++) {
pq.offer(i);
}
System.out.println(pq); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
System.out.println(pq.poll()); // 0
System.out.println(pq); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
}
Note: Some platforms won’t provide proper support for Thread priorities and PriorityQueues.
Example2
package practice.collec;
import java.util.Comparator;
import java.util.PriorityQueue;
public class PriorityQueueDemo2 {
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue(15, new MyCompartor());
pq.offer("A");
pq.offer("Z");
pq.offer("L");
pq.offer("B");
System.out.println(pq); // [Z, L, B, A]
}
}
class MyCompartor implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = obj1.toString();
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}
v1.6 Enhancements in Collection Framework
As part of v1.6 the following two concepts introduced in Collection Framework
1) NavigableSet
2) NavigableMap
NavigableSet(I)
 It is the child interface of SortedSet and it defines several methods for Navigation purposes.
NavigableSet defines the following methods
floor(Object e) – It returns highest element which is <= e
lower(Object e) – It returns highest element which is < e
ceiling(Object e) – It returns lowest element which is >= e
higher(Object e) – It returns lowest element which is > e
pollFirst() – Remove and return first element
pollLast() – Remove and return last element
descendingSet() – It returns NavigableSet in reverse order

Example
package practice.collec;
import java.util.TreeSet;
public class NavigableSetDemo {
public static void main(String[] args) {
TreeSet<Integer> t = new TreeSet<Integer>();
t.add(1000);
t.add(2000);
t.add(3000);
t.add(4000);
t.add(5000);
System.out.println(t); // [1000, 2000, 3000, 4000, 5000]
System.out.println(t.ceiling(2000)); // 2000
System.out.println(t.higher(2000)); // 3000
System.out.println(t.floor(3000)); // 3000
System.out.println(t.lower(3000)); // 2000
System.out.println(t.pollFirst()); // 1000
System.out.println(t); // [2000, 3000, 4000, 5000]
System.out.println(t.pollLast()); // 5000
System.out.println(t); // [2000, 3000, 4000]
System.out.println(t.descendingSet()); // [4000, 3000, 2000]
}
}

NavigableMap(I)
 NavigableMap is the child interface of SortedMap, it defines several method for Navigation
purposes
NavigableMap defines the following methods
floorKey(Object e) – It returns highest Key which is <= e
lowerKey(Object e) – It returns highest Key which is < e
ceilingKey(Object e) – It returns lowest Key which is >= e
higherKey(Object e) – It returns lowest Key which is > e
pollFirstEntry() – Remove and return first Entry
pollLastEntry() – Remove and return last Entry
descendingMap() – It returns NavigableMap in reverse order
Example
package practice.map;
import java.util.TreeMap;
public class NavigableMapDemo {
public static void main(String[] args) {
TreeMap<String, String> t = new TreeMap<String, String>();
t.put("b", "banana");
t.put("c", "cat");
t.put("a", "apple");
t.put("d", "dog");
t.put("g", "gun");
System.out.println(t); // {a=apple, b=banana, c=cat, d=dog, g=gun}
System.out.println(t.ceilingKey("c")); // c
System.out.println(t.higherKey("e")); // g
System.out.println(t.floorKey("e")); // d
System.out.println(t.lowerKey("e")); // d
System.out.println(t.pollFirstEntry()); // a=apple
System.out.println(t.pollLastEntry()); // g=gun
System.out.println(t.descendingMap()); // {d=dog, c=cat, b=banana}
System.out.println(t); // {b=banana, c=cat, d=dog}
}
}

Utility Classes
Collections
Collections class defines several Utility methods for Collection Objects. Like Sorting, Searching,
Reversing…
Sorting Elements of List
Collections class defines the following two sort methods
public static void sort(List list) – To sort based on Default Natural Sorting order.
 In this case List should compulsory contain Homogenous and Comparable objects
otherwise we will get Runtime Exception saying ClassCastException
 List should not contain null otherwise we will get Runtime Exception saying
NullPointerException
public static void sort(List list, Comparator c) – To sort based on Customized sorting
Order
Example – Default Natural Sorting Order
import java.util.*;
public class CollectionsSortDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add("Z");
l.add("A");
l.add("K");
l.add("N");
l.add(new Integer(10)); // RE: ClassCastException
l.add(null); // RE: NullPointerException
System.out.println("Before: " + l); // Before: [Z, A, K, N]
Collections.sort(l);
System.out.println("After: " + l); // After: [A, K, N, Z]
} }
Example – Customized Sorting Order
package practice.collec;
import java.util.*;
public class CollectionsSortDemo2 {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add("Z");
l.add("A");
l.add("K");
l.add("L");
System.out.println("Before: "+l); // Before: [Z, A, K, L]
Collections.sort(l,new MyComparator7());
System.out.println("After: "+l); // After: [Z, L, K, A]
}
}
class MyComparator7 implements Comparator{
public int compare(Object obj1, Object obj2) {
String s1 = (String)obj1;
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}

Searching Elements of List


Collections class defines the following binary search methods
public static int binarySearch(List list, Object target) – If the list is sorted
according to Default natural sorting order then we have to use this method
public static int binarySearch(List list, Object target, Comparator c) – We have to use
this method if the list is sorted according to customized sorting order

Conclusions
 The above search methods internally will use binary search algorithm
 Successful search returns index
 Unsuccessful search returns insertion point
 Insertion point is the location where we can place target element in the sorted List
 Before calling binaySearch() compulsory list should be sorted otherwise we will get unpredictable
results
 If the list is sorted according to Comparator then at the time of search operation also we have to
pass same comparator object otherwise we will get Unpredictable results
Example – Seraching based on Default Natural Sorting order (Comparable)
import java.util.*;
public class CollectionsSearchDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add("Z");l.add("A");l.add("M");l.add("K");l.add("a");
System.out.println(l); // [Z, A, M, K, a]
Collections.sort(l);
System.out.println(l); // [A, K, M, Z, a]
System.out.println(Collections.binarySearch(l, "Z")); // 3
System.out.println(Collections.binarySearch(l, "J")); // -2
} }
Example – Searching based on Customized Sorting Order (Comparator)
package practice.collec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class CollectionsSearchDemo2 {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(15);
l.add(0);
l.add(20);
l.add(10);
l.add(5);
System.out.println(l); // [15, 0, 20, 10, 5]
Collections.sort(l, new MyComparator8());
System.out.println(l); // [20, 15, 10, 5, 0]
System.out.println(Collections.binarySearch(l, 10, new MyComparator8()));
// 2
System.out.println(Collections.binarySearch(l, 13, new MyComparator8()));
// -3
System.out.println(Collections.binarySearch(l, 17)); // -6 | unpredictable
}
}
class MyComparator8 implements Comparator {
public int compare(Object obj1, Object obj2) {
Integer i1 = (Integer) obj1;
Integer i2 = (Integer) obj2;
return i2.compareTo(i1);
}
}
Note: For the List of n elements, in the case of binary search method
 Successful search result range 0 to n-1
 Unsuccessful search result range –(n+1) to n-1
 Total result range –(n+1) to (n-1)
Reversing Elements for List
Collections class defines the following reverse method to reverse elements of list.
public static void reverse(List list)

Example
package practice.collec;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsReverseDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList();
l.add(15);l.add(0);l.add(20);
l.add(10);l.add(5);
System.out.println(l); // [15, 0, 20, 10, 5]
Collections.reverse(l);
System.out.println(l); // [5, 10, 20, 0, 15]
}
}
reverse() vs reverseOrder()
 We can use reverse() to reverse order of elements of list
 We can use reverseOrder() to get reversed Comparator
Comparator c1 = Collections.reverseOrder(c);
c | Ascending order | c1 | Descending order

Arrays
Arrays class is a Utility class to define several utility methods for Array objects
Sorting Elements of Array
Arrays class defines the following sort methods to sort elements of Primitive and Object type arrays
public static void sort(primitive[] p) – To sort according to Natural Sorting order
public static void sort(Object[] o) – To sort according to Natural sorting order
public static void sort(Object[] o, Comparator c) – To sort according to Customized
sorting order

package practice.collec;
import java.util.*;
public class ArraysSortDemo {
public static void main(String[] args) {
int[] a = { 10, 5, 20, 11, 6 };
System.out.println("Primitive Array Before Sorting");
for (int a1 : a) {
System.out.println(a1); // 10 5 20 11 6
}
Arrays.sort(a);
System.out.println("Primitive Array After Sorting");
for (int a1 : a) {
System.out.println(a1); // 5 6 10 11 6
}
String[] s = { "A", "Z", "B" };
System.out.println("Object Array Before Sorting");
for (String s1 : s) {
System.out.println(s1); // A Z B
}
Arrays.sort(s);
System.out.println("Object Array After Sorting");
for (String s1 : s) {
System.out.println(s1); // A B Z
}
Arrays.sort(s, new MyComparator9());
System.out.println("Object Array After Customized Sorting");
for (String s1 : s) {
System.out.println(s1); // Z B A
}
}}
class MyComparator9 implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = (String) obj1;
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}
Note: We can sort primitive arrays only based on Default Natural Sorting Order whereas we can sort Object arrays
either based on Default Natural Sorting Order or based on Customized sorting order
Searching Elements of Array
Arrays class defines the following Binary Search methods
public static int binarySearch(primitive[] a, primitive target)
public static int binarySearch(Object[] a, Object target)
public static int binarySearch(Object[]a, Object target, Comparator c)

Note: All rules of Arrays of binarySearch() method are exactly same as Collections class
binaraySearch()

Example
package practice.collec;
import java.util.Arrays;
import java.util.Comparator;
public class ArraysSearchDemo {
public static void main(String[] args) {
int[] a = { 10, 5, 20, 11, 6 };
Arrays.sort(a); // sort Default Natural Sorting Order
System.out.println(Arrays.binarySearch(a, 6)); // 2
System.out.println(Arrays.binarySearch(a, 14)); // -5
String[] s = { "A", "Z", "B" };
Arrays.sort(s); // sort Default Natural Sorting Order
System.out.println(Arrays.binarySearch(s, "Z")); // 2
System.out.println(Arrays.binarySearch(s, "S")); // -3
Arrays.sort(s, new MyComparator10());
System.out.println(Arrays.binarySearch(s, "Z",
new MyComparator10())); // 0
System.out.println(Arrays.binarySearch(s, "S",
new MyComparator10())); // -2
System.out.println(Arrays.binarySearch(s, "N")); // unpredictable result
}
}
class MyComparator10 implements Comparator {
public int compare(Object obj1, Object obj2) {
String s1 = (String) obj1;
String s2 = obj2.toString();
return s2.compareTo(s1);
}
}
Conversion of Array to List
public static List asList(Object[] o)
 This method won’t create an independent List object, for the existing Array we are getting List view
String[] s = { "A", "Z", "B" };
List l = Arrays.asList(s);

 By using Array reference if we perform any change automatically that change will be reflected to the
List. Similarly, by using List reference if we perform any change that change will be reflected
automatically to the Array.
 By using List reference we can’t perform any operation which varies the size. Otherwise we will get
runtime exception saying UnsupportedOperationException
String[] s ={"A","Z","B"};
List l = Arrays.asList(s);
l.add("M"); // RE: UnsupportedOperationException
l.remove(1); // RE: UnsupportedOperationException
l.set(1, "N"); // Valid

 By using List reference we are not allowed to replace with Heterogeneous objects otherwise we will
get Runtime Exception saying ArrayStoreException
String[] s ={"A","Z","B"};
List l = Arrays.asList(s);
l.set(1, new Integer(10));// RE: ArrayStoreException

Example
package practice.collec;
import java.util.Arrays;
import java.util.List;
public class ArraysAsListDemo {
public static void main(String[] args) {
String[] s = { "A", "Z", "B" };
List l = Arrays.asList(s);
System.out.println(l); // [A, Z, B]
s[0] = "K";
System.out.println(l); // [K, Z, B]
l.set(1, "N");
for (String s1 : s) {
System.out.println(s1); // K N B
}
l.add("M"); // RE: UnsupportedOperationException
l.remove(1); // RE: UnsupportedOperationException
l.set(1, new Integer(10)); // RE: ArrayStoreException
}
}

Anda mungkin juga menyukai