Set Interface in Java – HashSet , SortedSet Interface , LinkedHashSet

Being a child Interface of Collection Interface, we will use Set when we want to represent a group of individual objects as a single entity, where no duplicate elements are allowed and insertion order is not preserved.

Being a child interface of Collection Interface, all methods declared in Collection Interface are by-default available in Set (Interface). Other than this, there is no method in Set Interface.


SET Interface

SET in Java


HashSet in Java:

HashSet has the following features :

  • The underlined data structure for HashSet is Hash Table.
  • Duplicate elements are not allowed in HashSet.
  • Insertion order is not preserved in HashSet. Based on Hash Codes objects will be inserted.
  • ‘null’ insertion is possible in HashSet, but we can insert ‘null’ only once as duplicate objects are not allowed.
  • Heterogeneous elements we can insert in HashSet.
  • Serializable and Clonable is there in HashSet but Random Access is not there.
  • HashSet is the best choice if our frequent operation is searching.

Note : When we are going to add duplicate element in HashSet, we will not get any exception or compile time or runtime error. Just only add() method will returns ‘False’ as return type of add() method is boolean.

As example,

HashSet H = new HashSet();
System.out.println(H.add(“X”));	// add() will return ‘True’
System.out.println(H.add(“X”));	// add() will return ‘False’

Hash Set Constructors:

1)  HashSet H = new HashSet()

It creates a new HashSet object with default initial capacity 16 and default fill ratio (Load Factor) 0.75.
Fill ratio means, after filling 75% (as in case of HashSet default fill ratio is 0.75) amount of a HashSet, a new bigger HashSet is going to be created.

2) HashSet H = new HashSet(int initial_capacity)

Creates a new HashSet object with initial capacity specified by initial_capacity with default fill ratio 0.75. 

3) HashSet H = new HashSet(int initial_capacity, float fill_ratio)

Creates a new HashSet object with initial capacity specified by initial_capacity and fill ratio specified by fill_ratio.

4) HashSet H = new HashSet(Collection c)

This constructor creates an equivalent HashSet object for a given Collection object. If there is duplicate elements in the collection object, then in the HashSet object duplicate elements will be removed.


Now let us take an example program on HashSet :

import java.util.*;
class HashDemo
{
	public static void main(String[] args)
	{
		HashSet H = new HashSet();
		System.out.println(H.add(“J”));		// add() method returns ‘True’
		System.out.println(H.add(“K”));		// add() method returns ‘True’
		System.out.println(H.add(150));		// add() method returns ‘True’
		System.out.println(H.add(null));		// add() method returns ‘True’
		System.out.println(H.add(150));		// add() method returns ‘False’
		System.out.println(H);
		// Output : [null, 150, J, K]
	}
}

When we run this code we will get the following output :

true
true
true
true
false
[null, 150, J, K]

LinkedHashSet in Java:

LinkedHashSet is child class of HashSet and it is exactly same as HashSet (including constructors and methods), but it differs in only the following areas :

Difference Between LinkedHashSet and HashSet

              LinkedHashSet                           HashSet
The underlined data structure in case of LinkedHashSet is LinkedList and HashTable The underlined data structure in HashSet is HashTable.
Insertion order is preserved in LinkedHashSet. Insertion Order is not preserved in HashSet.
LinkedHashSet was introduced in JAVA in version 1.4 HashSet was introduced in JAVA version 1.2

In the example program, let’s replace HashSet with LinkedHashSet and see the result :

import java.util.*;
class HashDemo
{
	public static void main(String[] args)
	{
		LinkedHashSet H = new LinkedHashSet();
		System.out.println(H.add(“J”));		// add() method returns ‘True’
		System.out.println(H.add(“K”));		// add() method returns ‘True’
		System.out.println(H.add(150));		// add() method returns ‘True’
		System.out.println(H.add(null));		// add() method returns ‘True’
		System.out.println(H.add(150));		// add() method returns ‘False’
		System.out.println(H);
		// Output : [J, K, 150, null]
	}
}

When we run this code we will get the following output :

true
true
true
true
false
[J, K, 150, null]

Note : In general we can use LinkedHashSet to develop Cache based applications where duplicates are not allowed and insertion order must be preserved.


SortedSet Interface in Java

SortedSet is the child interface of Set (Interface). If we want to represent a group of individual objects according to some sorting order without keeping duplicate elements, then we will use SortedSet.

Methods:

SortedSet (INTERFACE) defines the following specific methods :

  • Object first() : This method returns the first object from the SortedSet.
  • Object last() : This method returns the last object from the SortedSet.
  • SortedSet headSet(Object obj) : This method returns a SortedSet with the elements which are less than the object obj in the given SortedSet.
  • SortedSet tailSet(Object obj) : This method returns a SortedSet with the elements which are greater than or equals with the object obj in the given SortedSet.
  • SortedSet subset(Object obj1, Object obj2) : This method returns a SortedSet with elements starting from obj1 to the previous element of obj2.
  • Comparator comparator() : This method returns a comparator object that describes the underlying sorting technique in the given SortedSet. If the SortedSet is using default natural sorting technique, then this method will return null.

Note : Default natural sorting order for numbers is “Ascending Order”, For string objects default natural sorting order is “Alphabetical Order”.