Main differences between a HashSet and TreeSet are:
1. Ordering: In a HashSet elements are stored in a random
order. In a TreeSet, elements are stored according to
natural ordering.
2. Null Value Element: We can store null value object in a
HashSet. A TreeSet does not allow to add a null value
object.
3. Performance: HashSet performs basic operations like
add(), remove(), contains(), size() etc in a constant size
time. A TreeSet performs these operations at the order of
log(n) time.
4. Speed: A HashSet is better than a TreeSet in performance
for most of operations like add(), remove(), contains(),
size() etc .
5. Internal Structure: a HashMap in Java internally backs a
HashSet. A NavigableMap backs a TreeSet internally.
6. Features: A TreeSet has more features compared to a
HashSet. It has methods like pollFirst(), pollLast(), first(),
last(), ceiling(), lower() etc.
7. Element Comparison: A HashSet uses equals() method for
comparison. A TreeSet uses compareTo() method for
comparison to maintain ordering of elements.