Collections Framework
Advanced

What is the difference between HashSet and TreeSet?

HashSet and TreeSet differ mainly in ordering and performance:

  • HashSet: uses a hash table, does not guarantee any ordering, and provides O(1) average time complexity for basic operations
  • TreeSet: uses a red-black tree, maintains sorted order (natural order or via a comparator), and provides O(log n) time complexity

HashSet is preferred for fast lookups, while TreeSet is useful when you need sorted data or ordered traversal.