HashSet, LinkedHashSet and TreeSet in Java

Set cares about uniqueness. It doesn’t allow duplications. Here “equals ( )” method is used to determine whether two objects are identical or not.

HashSet:

  • Unordered and unsorted.
  • Uses the hash code of the object to insert the values.
  • Use this when the requirement is “no duplicates and don’t care about the order”.

Example: 

public class Fruit {
 public static void main(String[] args) {
  HashSet < String > names = new HashSet <= String > ();
  names.add(“banana”);
  names.add(“cherry”);
  names.add(“apple”);
  names.add(“kiwi”);
  names.add(“banana”);
  System.out.println(names);
 }
}

Output:

[banana, cherry, kiwi, apple]

Doesn’t follow any insertion order. Duplicates are not allowed.

LinkedHashSet:

  • An ordered version of the hash set is known as Linked Hash Set.
  • Maintains a doubly-Linked list of all the elements.
  • Use this when the iteration order is required.

Example: 

public class Fruit {
 public static void main(String[] args) {
  LinkedHashSet < String > names = new LinkedHashSet < String > ();
  names.add(“banana”);
  names.add(“cherry”);
  names.add(“apple”);
  names.add(“kiwi”);
  names.add(“banana”);
  System.out.println(names);
 }
}

Output:

[banana, cherry, apple, kiwi]

Maintains the insertion order in which they have been added to the Set. Duplicates are not allowed.

TreeSet:

  • It is one of the two sorted collections.
  • Uses “Read-Black” tree structure and guarantees that the elements will be in ascending order.
  • We can construct a tree set with the constructor by using a comparable (or) comparator.

Example: 

public class Fruits {
 public static void main(String[] args) {
  TreeSet < String > names = new TreeSet < String > ();
  names.add(“cherry”);
  names.add(“banana”);
  names.add(“apple”);
  names.add(“kiwi”);
  names.add(“cherry”);
  System.out.println(names);
 }
}

Output:

[apple, banana, cherry, kiwi]

TreeSet sorts the elements in ascending order. And duplicates are not allowed.

Top 50+ Java Interview Questions with Answers

We covered nearly 50 + primary Java interview questions in this tutorial for fresh and experienced candidates.  Q.1- What is… Read More

4 years ago