1. Home
  2. Interview Questions
  3. Java
  4. 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

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best 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 uses hashCode() and equals() 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 a Comparator you pass in. Duplicates are detected using compareTo() or compare(), not equals(). It implements NavigableSet, so it offers methods such as first(), last(), floor(), ceiling(), headSet(), tailSet() and descendingSet().
FeatureHashSetLinkedHashSetTreeSet
OrderNone guaranteedInsertion orderSorted
add/remove/containsO(1) averageO(1) averageO(log n)
Null elementOne allowedOne allowedNot allowed with natural ordering (NullPointerException)
Duplicate checkhashCode + equalshashCode + equalscompareTo / compare
Thread-safeNoNoNo

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 Comparable to a TreeSet without a Comparator. This throws ClassCastException when 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 not hashCode() 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

All easy questions →

Related Questions

‹
Q14 of 18 · Java
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA