Set interface:

1. Set Interface in Java is present in java.util package. It extends the Collection interface.
2. If we want to represent group of individual objects as a single entity where duplicates are not allows and insertion order not preserved.
3. We can store at most one null value in Set.
4. Set interface doesn’t contain any new method and we have to use only Collection interface methods.

SetDiagram

HashSet:

  1. HashSet is one of the implementation class of Set interface present Since JDK 1.2.
  2. HashSet implements data Structure called Hashtable.
  3. HashSet doesn’t allow duplicate data.
  4. Insertion order is not preserved and Objects are inserted based on hash code.
  5. Heterogeneous objects are allowed.
  6. Accepts Single null element.
  7. Implements Cloneable, Serializable marker interface but not RandomAccess.
  8. HashSet is the best choice if the frequent operation is search operation. Search operation works based on hash code.
  9. Initial capacity is 16 and Fill ratio or load factor is 75%.

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.

HashSet h = new HashSet();
System.out.println(h.add("A")); //true
System.out.println(h.add("A")); //false

There are 4 overloaded constructors

public HashSet()

creates an empty HashSet object with default initial capacity 16 and default fill ratio or Load factor is 0.75

public HashSet(int initialCapacity)

creates an empty HashSet object with specified initial capacity and default fill ratio 0.75.

public HashSet (int initialCapacity, float loadFactor)

creates an empty HashSet object with specified initial capacity and customized fill ratio.

public HashSet (Collection<? extends E> c)

creates an equivalent HashSet for the given Collection.
This Constructor meant for inter conversion between Collection objects

FillRatio / LoadFactor:

After filling how much ration a new HashSet object will be created, this ratio is called FillRatio / LoadFactor.
For example, FillRatio 0.75 means, after filling 75% ratio, a new HashSet object will be created.

//Program using HashSet
import java.util.*;
class HashSetDemo{
    public static void main(String[] args){
        HashSet<Stringhs = new HashSet<String>();
        hs.add("Java");
        hs.add("Servlets");
        hs.add("JDBC");
        hs.add("Spring");
        hs.add("null");
        hs.add("Hibernate");
        System.out.println(hs.add("Spring"));
        System.out.println(hs);
    }
}

Output:
false
[Java, Hibernate, null, JDBC, Spring, Servlets]

LinkedHashSet:

  • LinkedHashSet is the child class of HashSet interface present since JDK 1.4.
  • LinkedHashSet is just like HashSet but it maintains insertion order.
  • It is exactly same as HashSet(including constructors) except underlined data structure.
  • HashSet implements data Structure called LinkedList + Hashtable.
//Program using LinkedHashSet
import java.util.*;
class LinkedHashSet{
    public static void main(String[] args){
        LinkedHashSet<Stringhs = new LinkedHashSet<String>();
        hs.add("Java");
        hs.add("Servlets");
        hs.add("JDBC");
        hs.add("Spring");
        hs.add("null");
        hs.add("Hibernate");
        System.out.println(hs.add("Spring"));
        System.out.println(hs);
    }
}

Output:
false
[Java, Servlets, JDBC, Spring, null, Hibernate]
Note: In general, we can use LinkedHashSet to develop cache-based applications where duplicates are not allowed and insertion order preserved.

SortedSet interface:

  1. SortedSet is the child interface of Set.
  2. 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 < obj.

SortedSet tailSet(Object obj)

returns SortedSet whose elements are >= obj.

SortedSet subSet(Object obj1, Object obj2)

returns SortedSet whose elements are >= obj1 and < 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 is Ascending order and for String objects is Alphabetical order.
For Example
{100, 101, 104, 106, 110, 115, 120}
first() ----> 100
last() ----> 120
headSet() ----> [100, 101, 104]
tailSet() ----> [106, 110, 115, 120]
subSet(101, 115) ----> [101, 104, 106, 110]

TreeSet:

  1. TreeSet is one of the implementation class of Set interface and present since JDK 1.2.
  2. TreeSet is not a hash-based collection, the data structure used is Balanced tree.
  3. TreeSet is mainly used for uniqueness and sorting. i.e.., TreeSet doesn’t store duplicate data and also
  4. Implements default natural sorting order.
  5. Insertion order not preserved.
  6. Heterogeneous objects are not allowed otherwise we will get runtime exception saying ClassCastException.
  7. TreeSet is Homogeneous i.e.., TreeSet can store only one type of data.
  8. All objects will be inserted on based on some sorting order it may be default natural sorting order or customized sorting order.
  9. TreeSet implements Serializable, Cloneable but not RandomAccess
  10. TreeSet cannot store even single null element.
  11. TreeSet either uses Comparable or Comparator interface.

Note:
Comparable is used for default natural sorting.
Comparator is used for Custom sorting.

Constructors:

public TreeSet()

creates an empty TreeSet object where the elements will be inserted according to default natural sorting order.

public TreeSet(Comparator c)

creates an empty TreeSet object where the elements will be inserted to according to customised sorting order specified by Comparator object

public TreeSet(Collection c)
public TreeSet(SortedSet s)

//Program using TreeSet
import java.util.*;
class TreeSetDemo{
    public static void main(String[] args){
        TreeSet<Stringts = new TreeSet<String>();
        ts.add("PK");
        ts.add("Prabhas");
        ts.add("NTR");
        ts.add("RC");
        ts.add("mb");
        //t.add(mew Integer(10)); // ClassCastException
        //t.add(null); // NullPointerException
        System.out.println(ts); // [NTR, PK, Prabhas, RC, mb]
    }
}

Output:
[NTR, PK, Prabhas, RC, mb]


Null acceptance:

  • For non-empty TreeSet we are trying to insert null then we will get NullPointerException.
  • For empty TreeSet first element as null is allowed. But after inserting that null if we are trying to insert other then we will get runtime exception saying NullPointerException

Note: Until 1.6V null is allows as first element to the empty TreeSet but from 1.7V onwards null is not allowed even as the first element that is "Null" such type of element is not applicable from 1.7V.

import java.util.TreeSet;
class TreeSetDemo{
    public static void main(String[] args){
        TreeSet t = new TreeSet();
        t.add(new StringBuffer("PK"));
        t.add(new StringBuffer("Prabhas"));
        t.add(new StringBuffer("NTR"));
        t.add(new StringBuffer("RC"));
        System.out.println(t);
    }
}

RE: ClassCastException

If we are depending on default natural sorting compulsory the objects should be Homogeneous and Comparable otherwise, we will get runtime exception saying ClassCastException.
An Object is said to be Comparable if and only if the corresponding class implements Comparable interface. String class and wrapper classes already implemented Comparable interface but StringBuffer class doesn’t implement Comparable interface. Hence, we got ClassCastException in the above example.

Comparison table of Set implemented classes:

Property HashSet LinkedHashSet TreeSet
Underlined Data structure Hashtable Combination of LinkedList + Hashtable Balanced tree
Duplicate objects Not allowed Not allowed Not allowed
Insertion order Not preserved Preserved Not preserved
Sorting order Not applicable Not applicable Applicable
Heterogeneous Objects Allowed Allowed Not allowed
Null acceptance Allowed Allowed For empty TreeSet as first element null is allowed but this rule is allowed until 1.6V only. From 1.7V null is not allowed even in first element.

As a part of 1.6 version one of the concept introduced in Collection framework is NavigableSet. For more information on NavigableSet go through to Map Interface.