Back to Lessons

Set Interface HashSet TreeSet

April 5, 2026

Set Interface

Collections without duplicate elements.

Set Examples

Set hashSet = new HashSet<>();
Set treeSet = new TreeSet<>();

hashSet.add("Java");
hashSet.add("Java"); // Duplicate ignored

treeSet.add("Zebra");
treeSet.add("Apple"); // Sorted order

Key Points

  • HashSet: unordered, fastest operations.
  • TreeSet: sorted, slower operations.
  • LinkedHashSet: maintains insertion order.
  • Elements must override equals() hashCode().