🗂️ Difference Between List and Set
Feature | List | Set |
---|---|---|
Order | Maintains insertion order | No guaranteed order (unless using LinkedHashSet) |
Duplicates | ✅ Allows duplicates | ❌ Does not allow duplicates |
Indexing | Indexed—can access elements by index (get(i) ) | Not indexed—no position-based access |
Implementations | ArrayList , LinkedList , Vector , etc. | HashSet , LinkedHashSet , TreeSet , etc. |
Best Use Case | When order & duplicates matter | When uniqueness is required |
💻 Code Example
📋 Using a List
(e.g., ArrayList
)
import java.util.*;
public class ListExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate allowed
System.out.println(fruits); // [Apple, Banana, Apple]
}
}
✅ Using a Set
(e.g., HashSet
)
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Apple"); // Duplicate ignored
System.out.println(fruits); // [Apple, Banana] (order may vary)
}
}
📌 When to Use Which?
Situation | Choose |
---|---|
You want to store elements with duplicates and preserve order | List |
You need a collection of unique values | Set |
You want to perform fast lookup, insert, delete, and don’t care about order | HashSet |
You need sorted unique elements | TreeSet |
🎯 Interview Takeaways
- ✅ Highlight that
List
allows duplicates and is indexed. - ✅ Stress that
Set
is all about uniqueness and often better for quick lookups. - ❌ Don’t confuse order preservation—only
LinkedHashSet
maintains insertion order, notHashSet
. - ✅ Mention performance:
HashSet
has O(1) average time complexity for basic operations. - Pro tip: Always choose the right collection based on the behavior you want—don’t just default to
ArrayList
.