Junior
What is the difference between TreeSet and HashSet?
sobes.tech AI
Answer from AI
TreeSet stores elements in sorted order and uses a red-black tree for this. HashSet does not guarantee element order and is based on a hash table.
Main differences:
- Element order:
TreeSetis ordered in ascending order,HashSetis not. - Performance: For most operations (
add,remove,contains),HashSethas an average complexity of O(1), whereasTreeSetis O(log n). - Implementation:
TreeSetusesTreeMap, where elements are stored as keys.HashSetusesHashMap, where elements are stored as keys, and values are dummy objects. - Null storage:
HashSetallows onenullelement.TreeSetdoes not allownull, as comparison of elements requires their heterogeneity. - Element comparison:
TreeSetrequires elements to implement theComparableinterface or a comparator to be provided.HashSetrequires correct implementation ofequals()andhashCode()methods for elements.
Example usage:
import java.util.HashSet;
import java.util.TreeSet;
public class SetDifference {
public static void main(String[] args) {
// HashSet - unordered
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
System.out.println("HashSet: " + hashSet); // Order may vary
// TreeSet - sorted
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
System.out.println("TreeSet: " + treeSet); // Always sorted
}
}
Comparison table:
| Aspect | HashSet | TreeSet |
|---|---|---|
| Order | Not guaranteed | Sorted |
| Performance | Average O(1) | Average O(log n) |
| Internal structure | Hash table (HashMap) | Red-black tree (TreeMap) |
| Null elements | Allows one null |
Does not allow null |
| Element requirements | equals(), hashCode() |
Comparable or Comparator |