Junior — Middle
What are the differences between LinkedHashSet and HashSet data structures in Java?
sobes.tech AI
Answer from AI
The main difference between LinkedHashSet and HashSet in Java lies in the order of element storage and performance:
-
HashSet — implements a set based on a hash table. Elements do not have a specific order when iterated over. The main advantage is high speed of add, remove, and search operations.
-
LinkedHashSet — extends HashSet but additionally maintains a linked list that preserves the insertion order of elements. When iterated, elements are returned in the order they were added.
Example:
HashSet<String> hashSet = new HashSet<>();
hashSet.add("apple");
hashSet.add("banana");
hashSet.add("cherry");
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
linkedHashSet.add("apple");
linkedHashSet.add("banana");
linkedHashSet.add("cherry");
System.out.println(hashSet); // Order may be arbitrary
System.out.println(linkedHashSet); // Will output [apple, banana, cherry]
Summary:
- Use HashSet if order does not matter and maximum performance is needed.
- Use LinkedHashSet if the insertion order of elements is important.