List vs Set vs Map

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • List: An ordered collection that allows duplicate elements. You can access elements by their integer index.
  • Set: An unordered collection that does not allow duplicate elements.
  • Map: An object that maps unique keys to values. It is a collection of Key-Value pairs, not single elements.

Concept

Choosing the right collection interface is the first step in Java data structure design.

1. List (e.g., ArrayList, LinkedList)

Use when order matters and you need to keep track of the exact sequence of insertion. Allows duplicates ([A, B, A]). Access elements via get(index).

2. Set (e.g., HashSet, TreeSet)

Use when uniqueness matters. If you try to add a duplicate element to a Set, the add() method simply returns false and ignores it. Most sets do not maintain insertion order.

3. Map (e.g., HashMap, TreeMap)

Use when you need a Dictionary or Lookup Table. It stores data as (Key, Value) pairs. Keys must be strictly unique, but values can be duplicated.

Examples

import java.util.*;

public class CoreInterfaces {
    public static void main(String[] args) {
        // --- LIST ---
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Apple"); // Duplicates allowed
        System.out.println("List: " + list); // Output: [Apple, Apple]
        System.out.println("Index 1: " + list.get(1)); // Indexed access

        // --- SET ---
        Set<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Apple"); // Duplicate ignored
        System.out.println("Set: " + set); // Output: [Apple]
        // set.get(0); // ERROR: Sets have no index!

        // --- MAP ---
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(1, "Orange"); // Overwrites key 1
        System.out.println("Map: " + map); // Output: {1=Orange, 2=Banana}
    }
}

Interview Questions

Q: If a Set does not allow duplicates, how does it know if an object is a duplicate?
A: A Set uses the equals() and hashCode() methods of the objects you are inserting to check for duplicates. If obj1.equals(obj2) is true, the Set considers them duplicates and rejects the second insertion. This is why overriding these methods is critical for custom objects.

Q: Can a Map have duplicate values? What about duplicate keys?
A: A Map can have duplicate values (e.g., map.put(1, "Apple"); map.put(2, "Apple"); is perfectly valid). However, it cannot have duplicate keys. If you put() a value using a key that already exists, the Map will overwrite the old value with the new value.