What is the difference between List and Set?

🗂️ Difference Between List and Set

FeatureListSet
OrderMaintains insertion orderNo guaranteed order (unless using LinkedHashSet)
Duplicates✅ Allows duplicates❌ Does not allow duplicates
IndexingIndexed—can access elements by index (get(i))Not indexed—no position-based access
ImplementationsArrayList, LinkedList, Vector, etc.HashSet, LinkedHashSet, TreeSet, etc.
Best Use CaseWhen order & duplicates matterWhen 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?

SituationChoose
You want to store elements with duplicates and preserve orderList
You need a collection of unique valuesSet
You want to perform fast lookup, insert, delete, and don’t care about orderHashSet
You need sorted unique elementsTreeSet

🎯 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, not HashSet.
  • ✅ 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.

Leave a Reply

Your email address will not be published. Required fields are marked *