- Home
- Interview Questions
- Java
- What is the difference between HashSet, LinkedHashSet and Tr…
Try answering first
In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.
1 Answer
Short answer: HashSet stores elements in a hash table with no ordering guarantee and O(1) average add, remove and contains. LinkedHashSet adds a linked list to preserve insertion order, and TreeSet keeps elements sorted in a red-black tree with O(log n) operations.
Detailed explanation
All three implement the Set interface, so none of them allows duplicates. They differ in how they store elements, how they decide whether two elements are duplicates, and what order you get when you iterate.
- HashSet is backed internally by a
HashMap. Each element is stored as a key, and a shared dummy object is stored as the value. It useshashCode()andequals()to detect duplicates. Iteration order is not defined and can change after a resize. - LinkedHashSet extends HashSet and is backed by a
LinkedHashMap. A doubly linked list runs through all entries, so iteration follows insertion order. Re-inserting an existing element does not change its position. It uses slightly more memory than HashSet. - TreeSet is backed by a
TreeMap, which is a red-black tree. Elements are kept sorted by natural ordering (Comparable) or by aComparatoryou pass in. Duplicates are detected usingcompareTo()orcompare(), notequals(). It implementsNavigableSet, so it offers methods such asfirst(),last(),floor(),ceiling(),headSet(),tailSet()anddescendingSet().
| Feature | HashSet | LinkedHashSet | TreeSet |
|---|---|---|---|
| Order | None guaranteed | Insertion order | Sorted |
| add/remove/contains | O(1) average | O(1) average | O(log n) |
| Null element | One allowed | One allowed | Not allowed with natural ordering (NullPointerException) |
| Duplicate check | hashCode + equals | hashCode + equals | compareTo / compare |
| Thread-safe | No | No | No |
When to use each:
- Use HashSet as the default when you only need uniqueness and fast lookups, for example checking whether a user ID has already been processed.
- Use LinkedHashSet when you need uniqueness and a predictable order, for example removing duplicates from a list while keeping the original sequence.
- Use TreeSet when you need sorted output or range queries, for example finding the next available time slot after a given time.
Example
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
List<String> cities = List.of("Pune", "Delhi", "Agra", "Pune", "Chennai");
Set<String> hash = new HashSet<>(cities);
Set<String> linked = new LinkedHashSet<>(cities);
TreeSet<String> tree = new TreeSet<>(cities);
System.out.println(hash); // order not guaranteed
System.out.println(linked); // [Pune, Delhi, Agra, Chennai]
System.out.println(tree); // [Agra, Chennai, Delhi, Pune]
System.out.println(tree.ceiling("B")); // Chennai
System.out.println(tree.headSet("Delhi")); // [Agra, Chennai]
}
}Common mistakes
- Assuming HashSet keeps insertion order or sorted order because small Integer values sometimes print in ascending order. That output is a side effect of how the hashes are spread across buckets and is not guaranteed.
- Adding objects that do not implement
Comparableto a TreeSet without a Comparator. This throwsClassCastExceptionwhen the set tries to compare them. - Using a Comparator that is inconsistent with
equals(). If you compare employees only by salary, two different employees with the same salary are treated as duplicates and one is silently dropped. - Saying TreeSet allows a null element. With natural ordering, adding null throws
NullPointerException.
Follow-up questions
- How does HashSet use HashMap internally to store its elements?
- What happens if you override
equals()but nothashCode()for objects stored in a HashSet? - How would you get a thread-safe sorted set in Java?
Interview tip: Name the backing map for each set (HashMap, LinkedHashMap, TreeMap). Then explain that TreeSet decides duplicates with compareTo, not equals. That one detail shows you understand the internals.
Reviewed by the Interview Questions editorial team · Last updated
How well did you know this?
Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.
Your Answer
More easy Java questions
Related Questions
- How is a lambda different from an anonymous inner class in Java beyond shorter syntax? · Java · 1 ans
- What makes an interface a functional interface, and what does @FunctionalInterface actually do? · Java · 1 ans
- How does HashMap work internally, including collisions, resizing and treeification in Java 8? · Java · 1 ans
- How do you implement a generic interface and its functions in Java? · Java · 1 ans
- What are the constraints in Java generics and why are they used? · Java · 1 ans
- How do abstract classes differ from interfaces in Java? · Java · 1 ans
- What are the advantages of using interfaces in Java? · Java · 1 ans
- How do final variables differ from static final variables? · Java · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)