Collections
Collections
Agenda
 1. Introduction
 2. Limitations of Object[] array
 3. Differences between Arrays and Collections ?
 4. 9(Nine) key interfaces of collection framework
      i. Collection
     ii. List
   iii. Set
    iv. SortedSet
     v. NavigableSet
    vi. Queue
   vii. Map
  viii. SortedMap
    ix. NavigableMap
 5. What is the difference between Collection and
    Collections ?
 6. In collection framework the following are legacy
    characters
 7. Collection interface
8. List interface
9. ArrayList
      o Differences between ArrayList and Vector ?
      o Getting synchronized version of ArrayList object
10.     LinkedList
11.     Vector
12.     Stack
13.     The 3 cursors of java
      1. Enumeration
      2. Iterator
      3. ListIterator
      o Compression of Enumeration , Iterator and
        ListIterator ?
14.     Set interface
15.     HashSet
16.     LinkedHashSet
17.     Diff b/w HashSet & LinkedHashSet
18.     SortedSet
19.     TreeSet
      o Null acceptance
20.     Comparable interface
21.     compareTo() method analysis
22.     Comparator interface
23.     Compression of Comparable and Comparator ?
24.     Compression of Set implemented class objects
25.     Map
26.     Entry interface
 27.       HashMap
       o   Differences between HashMap and Hashtable ?
       o   How to get synchronized version of HashMap
 28.       LinkedHashMap
 29.       IdentityHashMap
 30.       WeakHashMap
 31.       SortedMap
 32.       TreeMap
 33.       Hashtable
 34.       Properties
 35.       1.5v enhancements
       o   Queue interface
       o   PriorityQueue
 36.       1.6v Enhancements
       o   NavigableSet
       o   NavigableMap
 37.       Utility classes :
       o   Collections class
              Sorting the elements of a List
 Conclusions
       o   Arrays class
              Sorting the elements of array
Introduction:
 1. An array is an indexed collection of fixed no of
     homogeneous data elements. (or)
  2. An array represents a group of elements of same data
     type.
  3. The main advantage of array is we can represent huge
     no of elements by using single variable. So that
     readability of the code will be improved.
Limitations of Object[] array:
  1. Arrays are fixed in size that is once we created an array
     there is no chance of increasing (or) decreasing the size
     based on our requirement hence to use arrays concept
     compulsory we should know the size in advance which
     may not possible always.
  2. Arrays can hold only homogeneous data elements.
Example:
Student[] s=new Student[10000];
s[0]=new Student();//valid
s[1]=new Customer();//invalid(compile time error)
Compile time error:
Test.java:7: cannot find symbol
Symbol: class Customer
Location: class Test
s[1]=new Customer();
3) But we can resolve this problem by using object type
array(Object[]).
Example:
Object[] o=new Object[10000];
o[0]=new Student();
o[1]=new Customer();
4) Arrays concept is not implemented based on some data
structure hence ready-made methods support we can't expert.
For every requirement we have to write the code explicitly.
To overcome the above limitations we should go for
collections concept.
  1. Collections are growable in nature that is based on our
     requirement we can increase (or) decrease the size
     hence memory point of view collections concept is
     recommended to use.
  2. Collections can hold both homogeneous and
     heterogeneous objects.
  3. Every collection class is implemented based on some
     standard data structure hence for every requirement
     ready-made method support is available being a
     programmer we can use these methods directly without
     writing the functionality on our own.
Differences between Arrays and Collections ?
          Arrays                         Collections
                             1) Collections are growable in
1) Arrays are fixed in size.
                             nature.
2) Memory point of view      2) Memory point of view
arrays are not recommended collections are highly
to use.                      recommended to use.
3) Performance point of      3) Performance point of view
view arrays are              collections are not recommended
recommended to use.          to use.
4) Arrays can hold only       4) Collections can hold both
homogeneous data type         homogeneous and heterogeneous
elements.                     elements.
                              5) Every collection class is
5) There is no underlying
                              implemented based on some
data structure for arrays and
                              standard data structure and hence
hence there is no readymade
                              readymade method support is
method support.
                              available.
6) Arrays can hold both       6) Collections can hold only
primitives and object types. objects but not primitives.
Collection:
If we want to represent a group of objects as single entity
then we should go for collections.
Collection framework:
It defines several classes and interfaces to represent a group
of objects as a single entity.
          Java                         C++
Collection              Containers
Collection framework STL(Standard Template Library)
9(Nine) key interfaces of collection framework:
  1. Collection
  2. List
  3. Set
  4. SortedSet
  5. NavigableSet
  6. Queue
  7. Map
  8. SortedMap
  9. NavigableMap
Collection:
  1. If we want to represent a group of "individual objects"
     as a single entity then we should go for collection.
  2. In general we can consider collection as root interface
     of entire collection framework.
  3. Collection interface defines the most common methods
     which can be applicable for any collection object.
  4. There is no concrete class which implements Collection
     interface directly.
List:
  1. It is the child interface of Collection.
  2. If we want to represent a group of individual objects as
     a single entity where "duplicates are allow and insertion
     order must be preserved" then we should go for List
     interface.
Diagram:
Vector and Stack classes are re-engineered in 1.2 versions to
implement List interface.
Set:
  1. It is the child interface of Collection.
  2. If we want to represent a group of individual objects as
     single entity "where duplicates are not allow and
     insertion order is not preserved" then we should go for
     Set interface.
Diagram:
SortedSet:
 1. It is the child interface of Set.
 2. If we want to represent a group of individual objects as
    single entity "where duplicates are not allow but all
    objects will be insertion according to some sorting order
    then we should go for SortedSet.
    (or)
 3. If we want to represent a group of "unique objects"
    according to some sorting order then we should go for
    SortedSet.
NavigableSet:
 1. It is the child interface of SortedSet.
 2. It provides several methods for navigation purposes.
Queue:
  1. It is the child interface of Collection.
  2. If we want to represent a group of individual
     objects prior to processing then we should go for
     queue concept.
Diagram:
SortedMap:
  1. It is the child interface of Map.
  2. If we want to represent a group of objects as key value
     pairs "according to some sorting order of keys" then we
     should go for SortedMap.
NavigableMap:
1) It is the child interface of SortedMap and defines several
methods for navigation purposes.
What is the difference between Collection and
Collections ?
"Collection is an "interface" which can be used to represent a
group of objects as a single entity. Whereas "Collections is
an utility class" present in java.util package to define several
utility methods for Collection objects.
Collection--------------------interface
Collections------------------class
In collection framework the following are legacy
characters.
  1. Enumeration(I)
  2. Dictionary(AC)
  3. Vector(C)
  4. Stack(C)
  5. Hashtable(C)
  6. Properties(C)
Diagram:
Diagram:
Collection interface:
     If we want to represent a group of individual objects as
      a single entity then we should go for Collection
      interface. This interface defines the most common
      general methods which can be applicable for any
      Collection object.
     The following is the list of methods present in
      Collection interface.
        1. boolean add(Object o);
        2. boolean addAll(Collection c);
        3. boolean remove(Object o);
        4. boolean removeAll(Object o);
        5. boolean retainAll(Collection c);
           To remove all objects except those present in c.
        6. Void clear();
        7. boolean contains(Object o);
        8. boolean containsAll(Collection c);
        9. boolean isEmpty();
        10.    Int size();
        11.    Object[] toArray();
        12.    Iterator iterator();
There is no concrete class which implements Collection
interface directly.
List interface:
     It is the child interface of Collection.
     If we want to represent a group of individual objects as
      a single entity where duplicates are allow and insertion
      order is preserved. Then we should go for List.
     We can differentiate duplicate objects and we can
      maintain insertion order by means of index hence
    "index play very important role in List".
List interface defines the following specific methods.
  1. boolean add(int index,Object o);
  2. boolean addAll(int index,Collectio c);
  3. Object get(int index);
  4. Object remove(int index);
  5. Object set(int index,Object new);//to replace
  6. Int indexOf(Object o);
     Returns index of first occurrence of "o".
  7. Int lastIndexOf(Object o);
  8. ListIterator listIterator();
ArrayList:
  1. The underlying data structure is resizable array (or)
     growable array.
  2. Duplicate objects are allowed.
  3. Insertion order preserved.
  4. Heterogeneous objects are allowed.(except TreeSet ,
     TreeMap every where heterogenious objects are
     allowed)
  5. Null insertion is possible.
Constructors:
1) ArrayList a=new ArrayList();
Creates an empty ArrayList object with default initial
capacity "10" if ArrayList reaches its max capacity then a
new ArrayList object will be created with
        New capacity=(current capacity*3/2)+1
2) ArrayList a=new ArrayList(int initialcapacity);
Creates an empty ArrayList object with the specified initial
capacity.
3) ArrayList a=new ArrayList(collection c);
Creates an equivalent ArrayList object for the given
Collection that is this constructor meant for inter
conversation between collection objects. That is to dance
between collection objects.
Demo program for ArrayList:
import java.util.*;
class ArrayListDemo
{
     public static void main(String[] args)
     {
          ArrayList a=new ArrayList();
          a.add("A");
          a.add(10);
          a.add("A");
          a.add(null);
          System.out.println(a);//[A, 10, A, null]
          a.remove(2);
          System.out.println(a);//[A, 10, null]
          a.add(2,"m");
          a.add("n");
          System.out.println(a);//[A, 10, m, null,
n]
               }
}
System.out.println(a1 instanceof
Serializable ); //true
System.out.println(a2 instanceof Clonable); //true
              ArrayList                         Vector
                                  1) Every method is
1) No method is synchronized
                                  synchronized
2) At a time multiple Threads
                                  2) At a time only one Thread
are allow to operate on
                                  is allow to operate on Vector
ArrayList object and hence
                                  object and hence Vector
ArrayList object is not Thread
                                  object is Thread safe.
safe.
3) Relatively performance is      3) Relatively performance is
high because Threads are not      low because Threads are
required to wait.                 required to wait.
4) It is non legacy and           4) It is legacy and introduced
introduced in 1.2v                in 1.0v
Getting synchronized version of ArrayList object:
     Collections class defines the following method to return
      synchronized version of List.
      Public static List synchronizedList(list l);
      Example:
LinkedList:
 1. The underlying data structure is double LinkedList
 2. If our frequent operation is insertion (or) deletion in the
    middle then LinkedList is the best choice.
 3. If our frequent operation is retrieval operation then
    LinkedList is worst choice.
 4. Duplicate objects are allowed.
 5. Insertion order is preserved.
 6. Heterogeneous objects are allowed.
 7. Null insertion is possible.
 8. Implements Serializable and Cloneable interfaces but
    not RandomAccess.
Diagram:
Vector:
  1. The underlying data structure is resizable array (or)
     growable array.
  2. Duplicate objects are allowed.
  3. Insertion order is preserved.
  4. Heterogeneous objects are allowed.
  5. Null insertion is possible.
  6. Implements Serializable, Cloneable and RandomAccess
     interfaces.
Every method present in Vector is synchronized and hence
Vector is Thread safe.
Vector specific methods:
To add objects:
  1. add(Object o);-----Collection
  2. add(int index,Object o);-----List
  3. addElement(Object o);-----Vector
To remove elements:
  1. remove(Object o);--------Collection
  2. remove(int index);--------------List
  3. removeElement(Object o);----Vector
  4. removeElementAt(int index);-----Vector
  5. removeAllElements();-----Vector
  6. clear();-------Collection
To get objects:
  1. Object get(int index);---------------List
  2. Object elementAt(int index);-----Vector
  3. Object firstElement();--------------Vector
  4. Object lastElement();---------------Vector
Other methods:
  1. Int size();//How many objects are added
  2. Int capacity();//Total capacity
  3. Enumeration elements();
Constructors:
  1. Vector v=new Vector();
       o Creates an empty Vector object with default initial
          capacity 10.
       o Once Vector reaches its maximum capacity then a
Stack:
  1. It is the child class of Vector.
  2. Whenever last in first out(LIFO) order required then
     we should go for Stack.
Constructor:
It contains only one constructor.
Stack s= new Stack();
Methods:
  1. Object push(Object o);
     To insert an object into the stack.
  2. Object pop();
     To remove and return top of the stack.
  3. Object peek();
     To return top of the stack without removal.
  4. boolean empty();
     Returns true if Stack is empty.
  5. Int search(Object o);
     Returns offset if the element is available otherwise
     returns "-1"
Example:
import java.util.*;
class StackDemo
{
     public static void main(String[] args)
     {
          Stack s=new Stack();
          s.push("A");
          s.push("B");
          s.push("C");
          System.out.println(s);//[A, B, C]
          System.out.println(s.pop());//C
          System.out.println(s);//[A, B]
          System.out.println(s.peek());//A
          System.out.println(s.search("A"));//2
          System.out.println(s.search("Z"));//-1
          System.out.println(s.empty());//false
     }
}
Limitations of Iterator:
  1. Both enumeration and Iterator are single direction
     cursors only. That is we can always move only forward
     direction and we can't move to the backward direction.
  2. While iterating by Iterator we can perform only read
     and remove operations and we can't perform
     replacement and addition of new objects.
  3. To overcome these limitations sun people introduced
    listIterator concept.
ListIterator:
  1. ListIterator is the child interface of Iterator.
  2. By using listIterator we can move either to the forward
     direction (or) to the backward direction that is it is a bi-
     directional cursor.
  3. While iterating by listIterator we can perform
     replacement and addition of new objects in addition to
     read and remove operations
By using listIterator method we can create listIterator object.
public ListIterator listIterator();
ListIterator itr=l.listIterator();
(l is any List object)
ListIterator interface defines the following 9 methods.
  1. public boolean hasNext();
  2. public Object next(); forward
  3. public int nextIndex();
  4. public boolean hasPrevious();
  5. public Object previous(); backward
  6. public int previousIndex();
  7. public void remove();
  8. public void set(Object new);
  9. public void add(Object new);
Example:
import java.util.*;
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 itr=l.listIterator();
          while(itr.hasNext())
          {
               String s=(String)itr.next();
               if(s.equals("venki"))
               {
                    itr.remove();
               }
          }
          System.out.println(l);//[balakrishna,
chiru, nag]
     }
}
Case 1:
if(s.equals("chiru"))
{
itr.set("chran");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chran, nag]
Case 2:
if(s.equals("nag"))
{
itr.add("chitu");
}
Output:
[balakrishna, venki, chiru, nag]
[balakrishna, venki, chiru, nag, chitu]
The most powerful cursor is listIterator but its limitation is it
is applicable only for "List objects".
Compression of Enumeration Iterator and
ListIterator ?
 Property Enumeration Iterator                 ListIterator
1) Is it
            Yes           no             no
legacy ?
                          Applicable
2) It is
            Only legacy for any          Applicable for only
applicable
            classes.      collection     list objects.
for ?
                          object.
            Single        Single
3)          direction     direction
                                         Bi-directional.
Moment? cursor(forward cursor(forwar
            )             d)
            By using      By using
4) How to                                By using
            elements()    iterator()meth
get it?                                  listIterator() method.
            method.       od.
5)
                          Both read      Read/remove/
Accessibili Only read.
                          and remove. replace/add.
ty?
            hasMoreEleme hasNext()
6) Methods nt()           next()         9 methods.
            nextElement() remove()
Set interface:
  1. It is the child interface of Collection.
  2. If we want to represent a group of individual objects as
     a single entity where duplicates are not allow and
     insertion order is not preserved then we should go for
     Set interface.
Diagram:
Example:
import java.util.*;
class HashSetDemo
{
     public static void main(String[] args)
     {
          HashSet h=new HashSet();
          h.add("B");
          h.add("C");
          h.add("D");
          h.add("Z");
          h.add(null);
          h.add(10);
          System.out.println(h.add("Z"));//false
          System.out.println(h);//[null, D, B, C,
10, Z]
          }
}
LinkedHashSet:
  1. It is the child class of HashSet.
  2. LinkedHashSet is exactly same as HashSet except the
     following differences.
       HashSet                        LinkedHashSet
                          1) The underlying data structure is a
1) The underlying data
                          combination of LinkedList and
structure is Hashtable.
                          Hashtable.
2) Insertion order is not
                          2) Insertion order is preserved.
preserved.
3) Introduced in 1.2 v. 3) Introduced in 1.4v.
In the above program if we are replacing HashSet with
LinkedHashSet the output is [B, C, D, Z, null, 10].That is
insertion order is preserved.
Example:
import java.util.*;
class LinkedHashSetDemo
{
     public static void main(String[] args)
     {
          LinkedHashSet h=new LinkedHashSet();
          h.add("B");
          h.add("C");
          h.add("D");
          h.add("Z");
          h.add(null);
          h.add(10);
          System.out.println(h.add("Z"));//false
          System.out.println(h);//[B, C, D, Z,
null, 10]
          }
}
Constructors:
  1. TreeSet t=new TreeSet();
     Creates an empty TreeSet object where all elements will
     be inserted according to default natural sorting order.
  2. TreeSet t=new TreeSet(Comparator c);
     Creates an empty TreeSet object where all objects will
     be inserted according to customized sorting order
     specified by Comparator object.
  3. TreeSet t=new TreeSet(SortedSet s);
  4. TreeSet t=new TreeSet(Collection c);
Example 1:
import java.util.*;
class TreeSetDemo
{
     public static void main(String[] args)
     {
          TreeSet t=new TreeSet();
          t.add("A");
          t.add("a");
          t.add("B");
          t.add("Z");
          t.add("L");
          //t.add(new
Integer(10));//ClassCastException
          //t.add(null);//NullPointerException
          System.out.println(t);//[A, B, L, Z, a]
          }
}
Null acceptance:
     For the empty TreeSet as the 1st element "null"
      insertion is possible but after inserting that null if we are
      trying to insert any other we will get
      NullPointerException.
     For the non empty TreeSet if we are trying to insert null
      then we will get NullPointerException.
Example 2:
import java.util.*;
class TreeSetDemo
{
     public static void main(String[] args)
     {
          TreeSet t=new TreeSet();
          t.add(new StringBuffer("A"));
          t.add(new StringBuffer("Z"));
          t.add(new StringBuffer("L"));
          t.add(new StringBuffer("B"));
          System.out.println(t);
          }
}
Output:
Runtime Exception.
Note :
     Exception in thread "main"
      java.lang.ClassCastException: java.lang.StringBuffer
      cannot be cast to java.lang.Comparable
     If we are depending on default natural sorting order
      compulsory the objects should be homogeneous and
      Comparable otherwise we will get ClassCastException.
     An object is said to be Comparable if and only if the
      corresponding class implements Comparable interface.
     String class and all wrapper classes implements
      Comparable interface but StringBuffer class doesn't
      implement Comparable interface hence in the above
      program we are getting ClassCastException.
Comparable interface:
Comparable interface present in java.lang package and
contains only one method compareTo() method.
public int compareTo(Object obj);
Example:
obj1.compareTo(obj2);
Diagram:
Example 3:
class Test
{
     public static void main(String[] args)
     {
System.out.println("A".compareTo("Z"));//-25
System.out.println("Z".compareTo("K"));//15
     System.out.println("A".compareTo("A"));//0
          //System.out.println("A".compareTo(new
Integer(10)));
               //Test.java:8:
compareTo(java.lang.String) in java.lang.String
cannot
                be applied to (java.lang.Integer)
//System.out.println("A".compareTo(null));//NullPoi
nterException
     }
}
Diagram:
  1. If we want to represent a group of objects as "key-
     value" pair then we should go for Map interface.
  2. Both key and value are objects only.
  3. Duplicate keys are not allowed but values can be
     duplicated
  4. Each key-value pair is called "one entry".
Diagram:
HashMap:
  1. The underlying data structure is Hashtable.
  2. Duplicate keys are not allowed but values can be
     duplicated.
  3. Insertion order is not preserved and it is based on hash
     code of the keys.
  4. Heterogeneous objects are allowed for both key and
     value.
  5. Null is allowed for keys(only once) and for values(any
     number of times).
  6. It is best suitable for Search operations.
Differences between HashMap and Hashtable ?
          HashMap                         Hashtable
1) No method is
                            1) Every method is synchronized.
synchronized.
2) Multiple Threads can 2) Multiple Threads can't operate
operate simultaneously on simultaneously on Hashtable
HashMap object and hence object and hence Hashtable object
it is not Thread safe.      is Thread safe.
3) Relatively performance
                            3) Relatively performance is low.
is high.
                            4) Null is not allowed for both key
4) Null is allowed for both
                            and value otherwise we will get
key and value.
                            NullPointerException.
5) It is non legacy and     5) It is legacy and introduced in
introduced in 1.2v.         1.0v.
How to get synchronized version of HashMap:
By default HashMap object is not synchronized. But we can
get synchronized version by using the following method of
Collections class.
public static Map synchronizedMap(Map m1)
Constructors:
 1. HashMap m=new HashMap();
    Creates an empty HashMap object with default initial
    capacity 16 and default fill ratio "0.75".
 2. HashMap m=new HashMap(int initialcapacity);
 3. HashMap m =new HashMap(int initialcapacity, float
    fillratio);
 4. HashMap m=new HashMap(Map m);
Example:
import java.util.*;
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);//{nagarjuna=500,venkatesh=20
0,balaiah=800,chiranjeevi=700}
System.out.println(m.put("chiranjeevi",100));//700
          Set s=m.keySet();
System.out.println(s);//[nagarjuna,venkatesh,balaia
h,chiranjeevi]
           Collection c=m.values();
           System.out.println(c);//[500, 200, 800,
100]
           Set s1=m.entrySet();
System.out.println(s1);//[nagarjuna=500,venkatesh=2
00,balaiah=800,chiranjeevi=100]
          Iterator itr=s1.iterator();
          while(itr.hasNext())
          {
               Map.Entry m1=(Map.Entry)itr.next();
               System.out.println(m1.getKey()
+"......"+m1.getValue());
               //nagarjuna......500
     //venkatesh......200 //
                            //balaiah......800
//chiranjeevi......100
               if(m1.getKey().equals("nagarjuna"))
               {
                    m1.setValue(1000);
               }
          }
          System.out.println(m);
//{nagarjuna=1000,venkatesh=200,balaiah=800,chiranj
eevi=100}
     }
}
LinkedHashMap:
WeakHashMap:
It is exactly same as HashMap except the following
differences:
       In the case of normal HashMap, an object is not eligible
        for GC even though it doesn't have any references if it is
        associated with HashMap. That is HashMap dominates
        garbage collector.
       But in the case of WeakHashMap if an object does not
        have any references then it's always eligible for GC
        even though it is associated with WeakHashMap that is
    garbage collector dominates WeakHashMap.
Example:
import java.util.*;
class WeakHashMapDemo
{
     public static void main(String[] args)throws
Exception
     {
           WeakHashMap m=new WeakHashMap();
           Temp t=new Temp();
           m.put(t,"ashok");
           System.out.println(m);//{Temp=ashok}
           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
called");
     }
}
Output:
{Temp=ashok}
finalize() method called
{}
Diagram:
In the above program if we replace WeakHashMap with
normal HashMap then object won't be destroyed by the
garbage collector in this the output is
{Temp=ashok}
{Temp=ashok}
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.
    Sorting is possible only based on the keys but not based
     on values.
    SortedMap interface defines the following 6 specific
     methods.
       1. Object firsyKey();
       2. Object lastKey();
       3. SortedMap headMap(Object key);
       4. SortedMap tailMap(Object key);
       5. SortedMap subMap(Object key1,Object key2);
       6. Comparator comparator();
TreeMap:
 1. The underlying data structure is RED-BLACK Tree.
 2. Duplicate keys are not allowed but values can be
    duplicated.
 3. Insertion order is not preserved and all entries will be
    inserted according to some sorting order of keys.
 4. If we are depending on default natural sorting order
    keys should be homogeneous and Comparable
    otherwise we will get ClassCastException.
 5. If we are defining our own sorting order by Comparator
    then keys can be heterogeneous and non Comparable.
 6. There are no restrictions on values they can be
    heterogeneous and non Comparable.
 7. For the empty TreeMap as first entry null key is allowed
    but after inserting that entry if we are trying to insert
    any other entry we will get NullPointerException.
  8. For the non empty TreeMap if we are trying to insert an
     entry with null key we will get NullPointerException.
  9. There are no restrictions for null values.
Constructors:
  1. TreeMap t=new TreeMap();
     For default natural sorting order.
  2. TreeMap t=new TreeMap(Comparator c);
     For customized sorting order.
  3. TreeMap t=new TreeMap(SortedMap m);
  4. TreeMap t=new TreeMap(Map m);
Example 1:
import java.util.*;
class TreeMapDemo
{
     public static void main(String[] args)
     {
          TreeMap t=new TreeMap();
          t.put(100,"ZZZ");
          t.put(103,"YYY");
          t.put(101,"XXX");
          t.put(104,106);
          t.put(107,null);
          //t.put("FFF","XXX");//ClassCastException
     //t.put(null,"xxx");//NullPointerException
          System.out.println(t);//{100=ZZZ,
101=XXX, 103=YYY, 104=106, 107=null}
     }
}
Example 2:
import java.util.*;
class TreeMapDemo
{
     public static void main(String[] args)
     {
          TreeMap t=new TreeMap(new
MyComparator());
          t.put("XXX",10);
          t.put("AAA",20);
          t.put("ZZZ",30);
          t.put("LLL",40);
          System.out.println(t);//{ZZZ=30, XXX=10,
LLL=40, AAA=20}
     }
}
class MyComparator implements Comparator
{
     public int compare(Object obj1,Object obj2)
     {
          String s1=obj1.toString();
          String s2=obj2.toString();
          return s2.compareTo(s1);
     }
}
Hashtable:
    1. The underlying data structure is Hashtable.
    2. Insertion order is not preserved and it is based on hash
       code of the keys.
    3. Heterogeneous objects are allowed for both keys and
       values.
    4. Null key (or) null value is not allowed otherwise we
       will get NullPointerException.
    5. Duplicate keys are allowed but values can be
       duplicated.
  6. Every method present inside Hashtable is syncronized
     and hence Hashtable objet is Thread-safe.
Constructors:
  1. Hashtable h=new Hashtable();
     Creates an empty Hashtable object with default
     initialcapacity 11 and default fill ratio 0.75.
  2. Hashtable h=new Hashtable(int initialcapacity);
  3. Hashtable h=new Hashtable(int initialcapacity,float
     fillratio);
  4. Hashtable h=new Hashtable (Map m);
Example:
import java.util.*;
class HashtableDemo
{
     public static void main(String[] args)
     {
           Hashtable h=new Hashtable();
           h.put(new Temp(5),"A");
           h.put(new Temp(2),"B");
           h.put(new Temp(6),"C");
           h.put(new Temp(15),"D");
           h.put(new Temp(23),"E");
           h.put(new Temp(16),"F");
           System.out.println(h);//{6=C, 16=F, 5=A,
15=D, 2=B, 23=E}
     }
}
class Temp
{
     int i;
     Temp(int i)
     {
           this.i=i;
     }
     public int hashCode()
     {
          return i;
     }
     public String toString()
     {
          return i+"";
     }
}
Diagram:
Example:
import java.util.*;
import java.io.*;
class PropertiesDemo
{
     public static void main(String[] args)throws
Exception
     {
          Properties p=new Properties();
          FileInputStream fis=new
FileInputStream("abc.properties");
          p.load(fis);
          System.out.println(p);//{user=scott,
password=tiger, venki=8888}
          String s=p.getProperty("venki");
          System.out.println(s);//8888
          p.setProperty("nag","9999999");
          Enumeration e=p.propertyNames();
          while(e.hasMoreElements())
          {
               String s1=(String)e.nextElement();
               System.out.println(s1);//nag
                                //user
                                //password
                                //venki
          }
          FileOutputStream fos=new
FileOutputStream("abc.properties");
          p.store(fos,"updated by ashok for scjp
demo class");
     }
}
Property file:
Example:
import java.util.*;
import java.io.*;
class PropertiesDemo
{
     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 user=p.getProperty("user");
          String pwd=p.getProperty("pwd");
          Connection
con=DriverManager.getConnection(url, user, pwd);
          -----------------------------------------
----------------
          -----------------------------------------
---------------
          FileOutputStream fos=new
FileOutputStream("db.properties");
          p.store(fos,"updated by ashok for scjp
demo class");
     }
}
1.5 enhancements
Queue interface
Diagram:
//System.out.println(q.element());//NoSuchElementEx
ception
          for(int i=0;i<=10;i++)
          {
                q.offer(i);
          }
          System.out.println(q);//[0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10]
          System.out.println(q.poll());//0
          System.out.println(q);//[1, 3, 2, 7, 4,
5, 6, 10, 8, 9]
          }
}
Note: Some platforms may not provide proper supports for
PriorityQueue [windowsXP].
Example 2:
import java.util.*;
class PriorityQueueDemo
{
     public static void main(String[] args)
     {
          PriorityQueue q=new PriorityQueue(15,new
MyComparator());
          q.offer("A");
          q.offer("Z");
          q.offer("L");
          q.offer("B");
          System.out.println(q);//[Z, B, L, A]
          }
}
class MyComparator implements Comparator
{
     public int compare(Object obj1,Object obj2)
     {
          String s1=(String)obj1;
          String s2=obj2.toString();
          return s2.compareTo(s1);
     }
}
1.6v Enhancements :
NavigableSet:
  1. It is the child interface of SortedSet.
  2. It provides several methods for navigation purposes.
Diagram:
NavigableSet interface defines the following methods.
  1. ceiling(e);
     It returns the lowest element which is >=e.
  2. higher(e);
     It returns the lowest element which is >e.
  3. floor(e);
     It returns highest element which is <=e.
  4. lower(e);
     It returns height element which is <e.
  5. pollFirst ();
     Remove and return 1st element.
  6. pollLast ();
     Remove and return last element.
  7. descendingSet ();
     Returns SortedSet in reverse order.
Diagram:
Example:
import java.util.*;
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.pollLast());//5000
      System.out.println(t.descendingSet());//[4000,
3000, 2000]
           System.out.println(t);//[2000, 3000,
4000]
           }
}
NavigableMap:
It is the child interface of SortedMap and it defines several
methods for navigation purpose.
Diagram:
NavigableMap interface defines the following methods.
  1. ceilingKey(e);
  2. higherKey(e);
  3. floorKey(e);
  4. lowerKey(e);
  5. pollFirstEntry();
  6. pollLastEntry();
  7. descendingMap();
Example:
import java.util.*;
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}
          }
}
Diagram:
Collections class:
Collections class defines several utility methods for
collection objects.
Sorting the elements of a List:
Collections class defines the following methods to perform
sorting the elements of a List.
public static void sort(List l);
     To sort the elements of List according to default natural
      sorting order in this case the elements should be
      homogeneous and comparable otherwise we will get
      ClassCastException.
     The List should not contain null otherwise we will get
      NullPointerException.
public static void sort(List l,Comparator c);
     To sort the elements of List according to customized
      sorting order.
Program 1: To sort elements of List according to natural
sorting order.
import java.util.*;
class CollectionsDemo
{
     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));//ClassCastException
          //l.add(null);//NullPointerException
          System.out.println("Before
sorting :"+l);//[Z, A, K, N]
          Collections.sort(l);
          System.out.println("After
sorting :"+l);//[A, K, N, Z]
     }
}
Program 2: To sort elements of List according to customized
sorting order.
import java.util.*;
class CollectionsDemo
{
     public static void main(String[] args)
     {
          ArrayList l=new ArrayList();
          l.add("Z");
          l.add("A");
          l.add("K");
          l.add("L");
          l.add(new Integer(10));
          //l.add(null);//NullPointerException
          System.out.println("Before
sorting :"+l);//[Z, A, K, L, 10]
          Collections.sort(l,new MyComparator());
          System.out.println("After
sorting :"+l);//[Z, L, K, A, 10]
          }
}
class MyComparator implements Comparator
{
     public int compare(Object obj1,Object obj2)
     {
          String s1=(String)obj1;
          String s2=obj2.toString();
          return s2.compareTo(s1);
     }
}
System.out.println(Collections.binarySearch(l,"Z"))
;//3
System.out.println(Collections.binarySearch(l,"J"))
;//-2
             }
}
Diagram:
Program 2:
import java.util.*;
class CollectionsSearchDemo
{
     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 MyComparator());
          System.out.println(l);//[20, 15, 10, 5,
0]
System.out.println(Collections.binarySearch(l,10,ne
w MyComparator()));//2
System.out.println(Collections.binarySearch(l,13,ne
w MyComparator()));//-3
System.out.println(Collections.binarySearch(l,17));
//-6
          }
}
class MyComparator implements Comparator
{
     public int compare(Object obj1,Object obj2)
     {
          Integer i1=(Integer)obj1;
          Integer i2=(Integer)obj2;
          return i2.compareTo(i1);
     }
}
Diagram:
Conclusions:
  1. Internally these search methods will use binary search
     algorithm.
  2. Successful search returns index unsuccessful search
     returns insertion point.
  3. Insertion point is the location where we can place the
     element in the sorted list.
  4. Before calling binarySearch() method compulsory the
     list should be sorted otherwise we will get unpredictable
     results.
  5. If the list is sorted according to Comparator then at the
     time of search operation also we should pass the same
     Comparator object otherwise we will get unpredictable
     results.
Note:
For the list of n elements with respect to binary Search()
method.
     Successful search range is: 0 to n-1.
     Unsuccessful search results range is: -(n+1)to -1.
     Total result range is: -(n+1)to n-1.
Example:
System.out.println(Arrays.binarySearch(a,6));//1
System.out.println(Arrays.binarySearch(a,14));//-5
          String[] s={"A","Z","B"};
          Arrays.sort(s);
System.out.println(Arrays.binarySearch(s,"Z"));//2
System.out.println(Arrays.binarySearch(s,"S"));//-3
          Arrays.sort(s,new MyComparator());
System.out.println(Arrays.binarySearch(s,"Z",new
MyComparator()));//0
System.out.println(Arrays.binarySearch(s,"S",new
MyComparator()));//-2
System.out.println(Arrays.binarySearch(s,"N"));//-
4(unpredictable result)
          }
}
//l.add("ashok");//UnsupportedOperationException
     //l.remove(2);//UnsupportedOperationException
          //l.set(1,new
Integer(10));//ArrayStoreException
          }
}
Diagram:
BACK