☕ Java Q16 / 105

What is the difference between List and Set?

AI-Powered Answer ✓ Answered

In Java, `List` and `Set` are both interfaces that extend the `Collection` interface, but they represent fundamentally different types of collections with distinct characteristics and use cases. Understanding their differences is crucial for effective data structure selection.

Core Differences

The primary distinction between List and Set lies in their handling of element order and duplicate elements.

java.util.List

  • Ordered Collection: Elements are stored in a specific sequence, and their position matters. Elements can be accessed by their integer index.
  • Allows Duplicates: A List can contain multiple identical elements.
  • Implementations: Common implementations include ArrayList, LinkedList, and Vector.
  • Use Cases: Suitable when the order of elements is important, or when duplicates are allowed/expected (e.g., a log of events, a sequence of items in a shopping cart).

java.util.Set

  • Unordered Collection (generally): Elements are not stored in any specific order (though some implementations like LinkedHashSet maintain insertion order, and TreeSet maintains natural ordering). There is no index-based access.
  • Does Not Allow Duplicates: A Set guarantees that it will not contain duplicate elements. Attempting to add a duplicate element will typically result in no change to the Set (and the add() method returns false).
  • Implementations: Common implementations include HashSet, LinkedHashSet, and TreeSet.
  • Use Cases: Ideal for storing unique elements (e.g., a collection of unique user IDs, tags for an item, elements for mathematical set operations).

When to Use Which?

Use List when you need to maintain the order of elements, access elements by index, or allow duplicate elements. Use Set when you need to store only unique elements and the order of elements is not a primary concern (or when you want a sorted collection of unique elements, as with TreeSet).

FeatureListSet
OrderMaintains insertion order (indexed)Generally no guaranteed order (except LinkedHashSet, TreeSet)
DuplicatesAllows duplicate elementsDoes not allow duplicate elements
AccessBy indexNo index-based access
Interfacejava.util.Listjava.util.Set
Primary UseOrdered sequences, collections with duplicatesCollections of unique elements

Example Code

List Example

java
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Apple"); // Duplicates allowed
        fruits.add("Orange");

        System.out.println("List of fruits: " + fruits);
        System.out.println("Fruit at index 0: " + fruits.get(0));
        System.out.println("Does list contain Banana? " + fruits.contains("Banana"));
    }
}

Set Example

java
import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> uniqueColors = new HashSet<>();
        uniqueColors.add("Red");
        uniqueColors.add("Green");
        uniqueColors.add("Blue");
        uniqueColors.add("Red"); // Duplicate, will not be added

        System.out.println("Set of unique colors: " + uniqueColors);
        System.out.println("Does set contain Green? " + uniqueColors.contains("Green"));
        System.out.println("Size of set: " + uniqueColors.size()); // Will be 3, not 4
    }
}