Sobes.tech
Junior — Middle

What are the differences between HashSet and TreeSet collections in Java in terms of properties and usage?

sobes.tech AI

Answer from AI

HashSet and TreeSet are implementations of the Set interface in Java, but they differ in internal structure and behavior:

  • HashSet stores elements in a hash table. It provides fast access (add, remove, search operations approximately in O(1)), but does not guarantee the order of elements.
  • TreeSet is based on a red-black tree, and its elements are sorted either by their natural order or with the help of a Comparator. Operations take O(log n).

Usage:

  • If fast access is needed and order is not important — HashSet.
  • If sorting of elements is important — TreeSet.

Example:

Set<String> hashSet = new HashSet<>();
hashSet.add("banana");
hashSet.add("apple");
hashSet.add("orange");
System.out.println(hashSet); // Order is not guaranteed

Set<String> treeSet = new TreeSet<>();
treeSet.add("banana");
treeSet.add("apple");
treeSet.add("orange");
System.out.println(treeSet); // [apple, banana, orange]
What are the differences between HashSet and TreeSet… - sobes.tech