What are the differences between List, Set, and Map?
1. List
- Definition: An ordered collection (also known as a sequence) that allows duplicate elements.
- Key Characteristics:
- Maintains insertion order.
- Elements can be accessed by their index.
- Allows duplicate elements.
- Common Implementations:
ArrayList
(resizable array, fast for random access).LinkedList
(doubly-linked list, better for frequent insertions/deletions).Vector
(synchronized, legacy class).
- When to Use:
- When you need to preserve the order of elements and allow duplicates.
- For scenarios like maintaining a list of students, tasks, etc.
-
Example:
List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("A"); // Duplicates allowed System.out.println(list); // Output: [A, B, A]
2. Set
- Definition: A collection that does not allow duplicate elements.
- Key Characteristics:
- No duplicate elements are allowed.
- May or may not maintain order (depends on implementation).
- Common Implementations:
HashSet
(no guaranteed order, uses hash-based structure).LinkedHashSet
(maintains insertion order).TreeSet
(sorted order, based on aTreeMap
implementation).
- When to Use:
- When you need to store unique elements.
- For scenarios like storing unique IDs, removing duplicates, etc.
-
Example:
Set<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("A"); // Duplicate not added System.out.println(set); // Output: [A, B]
3. Map
- Definition: A collection of key-value pairs.
- Key Characteristics:
- Keys must be unique, but values can be duplicated.
- Does not implement
Collection
interface directly.
- Common Implementations:
HashMap
(unordered, uses hash table).LinkedHashMap
(maintains insertion order).TreeMap
(sorted order based on keys, uses a red-black tree).Hashtable
(synchronized, legacy class).
- When to Use:
- When you need to associate keys with values.
- For scenarios like dictionary-like storage, configurations, etc.
-
Example:
Map<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("A", 3); // Overwrites value for key "A" System.out.println(map); // Output: {A=3, B=2}
Key Differences
Feature | List | Set | Map |
---|---|---|---|
Duplicates | Allowed | Not allowed | Keys: Not allowed; Values: Allowed |
Order | Maintains insertion order | Depends on implementation | Depends on implementation |
Access | By index | Not by index | By key |
Structure | Single collection | Single collection | Key-Value pairs |
Null Handling | Allows multiple null s |
Allows one null (except TreeSet ) |
One null key, multiple null values (except TreeMap ) |
Interview Questions
- What happens if you add duplicate elements to a
Set
? - How is a
HashSet
different from aTreeSet
? - Can a
Map
have duplicate keys? Explain. - How does
ArrayList
differ fromLinkedList
in terms of performance?