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:
- add(E e) → adds element.
- remove(Object o) → removes element.
- contains(Object o) → checks if element exists.
- isEmpty() → checks if set is empty.
- size() → number of elements.
- clear() → removes all elements.
- 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:
- Sorted Order -> Stores elements in ascending (natural) order by default (like numbers in increasing order, strings in alphabetical order).
- You can also provide a custom comparator to define your own sorting.
- Unique Elements -> Like all sets, it does not allow duplicates.
- No Null Elements -> Unlike HashSet, TreeSet does not allow null values (will throw NullPointerException).
- Performance -> All basic operations (add, remove, search) take O(log n) time because of the Red-Black tree.
- 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:
- boolean add(E e) → Adds an element (returns false if already present).
- boolean remove(Object o) → Removes an element if present.
- boolean contains(Object o) → Checks if the element exists.
- void clear() → Removes all elements.
- int size() → Returns the number of elements.
- boolean isEmpty() → Checks if the set is empty.
Top comments (0)