DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

Set, HashSet, TreeSet and its Methods

Set:
A Set is a collection that does not allow duplicate elements. It models the mathematical set abstraction, which means each element is unique.

HashSet:
HashSet is a class in Java that implements the Set interface.
It stores unique elements, does not maintain insertion order, allows one null element, and provides fast operations using a hash table.

Key features:

  • HashSet is a class in java.util package.
  • It implements the Set interface.
  • It stores unique elements only (no duplicates allowed).
  • It does not maintain insertion order.
  • It allows one null element.
  • Internally, it uses a hash table for storage, which provides fast access.

Commonly Used Methods:

  1. add(E e) → adds element.
  2. remove(Object o) → removes element.
  3. contains(Object o) → checks if element exists.
  4. isEmpty() → checks if set is empty.
  5. size() → number of elements.
  6. clear() → removes all elements.
  7. iterator() → to iterate through elements.

TreeSet:

  • TreeSet is a class in Java that implements the NavigableSet interface and is based on a Red-Black Tree (a type of self-balancing binary search tree).
  • It is best when you need a sorted collection of unique elements and want efficient searching and range queries.
  • Requires elements to be comparable (either implement Comparable or provide a Comparator).
  • Slower than HashSet for add/search/remove (because HashSet is O(1), TreeSet is O(log n)).

Key Features of TreeSet:

  1. Sorted Order -> Stores elements in ascending (natural) order by default (like numbers in increasing order, strings in alphabetical order).
  2. You can also provide a custom comparator to define your own sorting.
  3. Unique Elements -> Like all sets, it does not allow duplicates.
  4. No Null Elements -> Unlike HashSet, TreeSet does not allow null values (will throw NullPointerException).
  5. Performance -> All basic operations (add, remove, search) take O(log n) time because of the Red-Black tree.
  6. Implements NavigableSet -> Provides additional methods like first(), last(), ceiling(), floor(), headSet(), tailSet(), subSet() etc.

TreeSet Methods:

TreeSet implements NavigableSet, so it has all methods of Set, SortedSet, and NavigableSet.

Basic Set Methods:

  1. boolean add(E e) → Adds an element (returns false if already present).
  2. boolean remove(Object o) → Removes an element if present.
  3. boolean contains(Object o) → Checks if the element exists.
  4. void clear() → Removes all elements.
  5. int size() → Returns the number of elements.
  6. boolean isEmpty() → Checks if the set is empty.

Top comments (0)