What is the difference between Set and List in Java?
List and Set are both sub-interfaces of Collection but with fundamentally different contracts around ordering and uniqueness.
A List is an ordered sequence. It maintains insertion order (or a deliberately sorted order), allows duplicate elements, and provides index-based access via get(int index). The primary implementations are ArrayList (random access, backed by an array, O(1) get) and LinkedList (sequential access, O(n) get, but O(1) insert/remove at a known position).
A Set models a mathematical set: no duplicate elements are permitted. The equals() and hashCode() contract determines what counts as a duplicate. HashSet offers O(1) average add/contains/remove but no ordering guarantee. LinkedHashSet preserves insertion order with O(1) operations. TreeSet maintains elements in natural or comparator-defined sorted order with O(log n) operations, implementing the NavigableSet interface.
The practical decision is: do you need uniqueness or do you need indexed positional access? If you need to store and retrieve by position, or duplicates are meaningful, use a List. If the semantics of your data require uniqueness (email addresses, active user IDs, feature flags), use a Set — it enforces the constraint automatically rather than relying on manual checks.
Performance difference for membership testing is significant. contains() on an ArrayList is O(n) because it scans every element. contains() on a HashSet is O(1) average. For large collections where membership checks are frequent, HashSet dramatically outperforms ArrayList.
Note that iterating a HashSet in a specific order is unreliable across JVM runs (hash seed randomization). If deterministic iteration order matters, prefer LinkedHashSet or TreeSet.
| Aspect | List | Set |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Order | Insertion order preserved | Depends on implementation (none/insertion/sorted) |
| Index access | Yes — get(int index) | No |
| contains() complexity | O(n) for ArrayList | O(1) avg for HashSet |
| Primary implementations | ArrayList, LinkedList | HashSet, LinkedHashSet, TreeSet |
| Use case | Ordered data, positional access, duplicates meaningful | Unique elements, fast membership testing |
Correctly states List allows duplicates with ordered access and Set enforces uniqueness, and names at least one implementation of each.
Adds contains() performance comparison, distinguishes HashSet vs LinkedHashSet vs TreeSet ordering guarantees, and gives a concrete use-case rationale for choosing one over the other.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment