Recent Posts

Thursday, 28 July 2016

Collection Framework Tutorial Part 3


3. Set Interface
* This can be used for representing a group of Individual objects where insertion order is not preserved and duplicate objects are not allowed.

* Set interface is child interface of Collection.

* This interface doesn’t contain any new method and we have to use only collection Interface methods.
     Set interface does not contain any new method we have to use only Collection interface methods.

i. HashSet
* The underlying data structure is Hashtable.

* Insertion order is not preserved and it is based on hash code of the objects.

* Duplicate objects are not allowed.

* If we are trying to insert duplicate objects we won't get compile time error and runtime error add() method simply returns false.

* Heterogeneous objects are allowed.

* Null insertion is possible.(only once)

* Implements Serializable and Cloneable interfaces but not RandomAccess.

* HashSet is best suitable, if our frequent operation is "Search".

Constructors
1. HashSet h = new HashSet()
     Creates an empty HashSet object with default initial value 16 and default fill ratio 0.75

2. HashSet h = new HashSet(int initialcapacity)

3. HashSet h = new HashSet(int initialCapacity, float fillratio)
     Here fillratio is 0 or 1.

4. HashSet h = new HashSet(Collection c)

Note
     After filling how much ratio new HashSet object will be created , The ratio is called "FillRatio" or "LoadFactor".
E.g
package com.ashok.collections.hashset;

import java.util.HashSet;

public class MyHashSet {
   public static void main(String args[]) {
      // HashSet declaration
      HashSet<string> hset = new HashSet<string>();
      // Adding elements to the HashSet
      hset.add("Ashok");
      hset.add("Vinod");
      hset.add("Dillesh");
      hset.add("Thiru");
      hset.add("Naresh");
      System.out.println(hset);
  
   // Addition of duplicate elements
      System.out.println(hset.add("Ashok"));

      System.out.println(hset);
  
      // Addition of null values
      hset.add(null);
      System.out.println(hset.add(null));
  
      // Displaying HashSet elements
      System.out.println(hset);
   }
}

Output
[Thiru, Ashok, Dillesh, Vinod, Naresh]
false
[Thiru, Ashok, Dillesh, Vinod, Naresh]
false
[null, Thiru, Ashok, Dillesh, Vinod, Naresh]
ii. LinkedHashSet
* It is the child class of HashSet.

* LinkedHashSet is exactly same as HashSet except the following differences.


E.g
package com.ashok.collections.hashset;

import java.util.LinkedHashSet;

public class MyLinkedHashSet {
   public static void main(String args[]) {
      // HashSet declaration
      LinkedHashSet<string> hset = new LinkedHashSet<string>();
      // Adding elements to the HashSet
      hset.add("Ashok");
      hset.add("Vinod");
      hset.add("Dillesh");
      hset.add("Thiru");
      hset.add("Naresh");
      System.out.println(hset);
  
      // Addition of duplicate elements
      System.out.println(hset.add("Ashok"));

      System.out.println(hset);
  
      // Addition of null values
      hset.add(null);
      System.out.println(hset.add(null));
  
      // Displaying HashSet elements
      System.out.println(hset);
   }
}
Note
    LinkedHashSet and LinkedHashMap commonly used for implementing "cache applications" where insertion order must be preserved and duplicates are not allowed.

iii. SortedSet
* It is child interface of Set.

* If we want to represent a group of "unique objects" where duplicates are not allowed and all objects must be inserting according to some sorting order then we should go for SortedSet interface.

* That sorting order can be either default natural sorting (or) customized sorting order.
     SortedSet interface define the following 6 specific methods.

1. Object first();
2. Object last();
3. SortedSet headSet(Object obj);
     Returns the SortedSet whose elements are <obj.
4. SortedSet tailSet(Object obj);
     It returns the SortedSet whose elements are >=obj.
5. SortedSet subset(Object o1,Object o2);
     Returns the SortedSet whose elements are >=o1 but <o2.
6. Comparator comparator();
     Returns the Comparator object that describes underlying sorting technique. If we are following default natural sorting order then this method returns null.

iv. TreeSet
* The underlying data structure is balanced tree.

* Duplicate objects are not allowed.

* Insertion order is not preserved and it is based on some sorting order of objects.

* Heterogeneous objects are not allowed if we are trying to insert heterogeneous objects then we will get ClassCastException.

* Null insertion is possible(only once).

Constructors
TreeSet t=new TreeSet();
     Creates an empty TreeSet object where all elements will be inserted according to default natural sorting order.

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.

TreeSet t=new TreeSet(SortedSet s);

TreeSet t=new TreeSet(Collection c);
E.g
package com.ashok.collections;

import java.util.TreeSet;

public class MyTreeSet {
   public static void main(String args[]) {
      // TreeSet of String Type
      TreeSet tset = new TreeSet();
      // Adding elements to TreeSet
      tset.add("Ashok");
      tset.add("Vinod");
      tset.add("Dillesh");
      tset.add("Thiru");
      tset.add("Mahesh");
      tset.add("Janaki");

      // Displaying TreeSet
      System.out.println(tset);
      
  // TreeSet of Integer Type
     TreeSet tset2 = new TreeSet();
     // Adding elements to TreeSet
     tset2.add(88);
     tset2.add(7);
     tset2.add(101);
     tset2.add(0);
     tset2.add(3);
     tset2.add(222);
     System.out.println(tset2);
   }
}
null Acceptance
     For the empty TreeSet as the first element null insertion is possible. But after inserting null if we are trying to insert any other element we will get NullPointerException.
     If the TreeSet already contains some elements if we are trying to insert null we will get NullPointerException.
E.g
import java.util.*;

class TreeSetDemo {
   public static void main(String arg[]) {
      TreeSet tset = new TreeSet();
      tset.add(new StringBuffer("A"));
      tset.add(new StringBuffer("B"));
      tset.add(new StringBuffer("T"));
      tset.add(new StringBuffer("Z"));
      System.out.println(tset);
   }
}
Output
R.E: ClassCastException
Note
* Exception in thread "main" java.lang.ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable

* If we are depending on natural sorting order compulsory the objects should be homogeneous and comparable other wise we will get class cast Exception.

* An object is said to be comparable(if and only if) the corresponding class has to implement comparable interface.

* All wrapper classes and String class already implemented comparable interface. But the String buffer doesn’t implement comparable interface. Hence in the above program we got class cast exception.

4. Comparable Interface
     It is available in java.lang package. This interface contains only one method compareTo()
public int compareTo(Object obj)
E.g
obj1.compareTo(obj2)

returns
–ve if obj1 has to come before obj2.
+ve if obj1 has to come after obj2.
0 if obj1 and obj2 are equal(Duplicate Objects).
E.g
package com.ashok.collections;

public class MyComparable {
   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
   }
}
Note
     While Inserting the objects into the TreeSet JVM internally uses compareTo() method if we are depending on natural sorting order.
     Sometimes we have to define our own customized sorting order, then we should go for comparator Interface.

5. Comparator Iterface
     By using comparator object we can define our own customized sorting. Comparator Interface is available in java.util package. This interface defines the following 2 methods.
1. public int compare(Object obj1, Object obj2)
returns
–ve if obj1 has to come before obj2
+ve if obj1 has to come after obj2
0 if obj1 and obj2 are equal.

2. public boolean equals(Object obj)
     When ever we are implementing comparator interface compulsory we should provide implementation for compare method. Implementing equals method is optional because it is already available from object class through inheritance.
E.g
package com.ashok.collections;

import java.util.*;

public class MyTreeSet {
   public static void main(String arg[]) {
      TreeSet tset = new TreeSet(new MyComparator());
      tset.add(85);
      tset.add(12);
      tset.add(68);
      tset.add(45);
      tset.add(0);
      System.out.println(tset);
   }
}

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;
   }
}

Output
[85, 68, 45, 12, 0]

Next Tutorial  Collection Framework Tutorial Part 4

Previous Tutorial  Collection Framework Tutorial Part 2

No comments:

Post a Comment