JavaIntermediate#collections

What is the difference between Set implementations HashSet, LinkedHashSet, and TreeSet?

HashSet offers O(1) operations with no ordering guarantee. LinkedHashSet maintains insertion order using a backing linked list. TreeSet keeps elements sorted (natural order or a Comparator) using a red-black tree, with O(log n) operations.

Example
Set<Integer> hs = new HashSet<>(List.of(3,1,2)); // unordered
Set<Integer> lhs = new LinkedHashSet<>(List.of(3,1,2)); // [3,1,2]
Set<Integer> ts = new TreeSet<>(List.of(3,1,2)); // [1,2,3]

Related Questions

1
JavaIntermediate#collections

What is the difference between Iterator and ListIterator?

Open
2
JavaIntermediate#collections

What is the difference between Deque and Queue?

Open
3
JavaBeginner#collections

How do you make a collection immutable?

Open