Sobes.tech
Junior

What is the difference between List and Set interfaces in Java?

sobes.tech AI

Answer from AI

The main differences between the List and Set interfaces in Java are as follows:

  • Order of elements:

    • List maintains the order of insertion. Elements have indices starting from 0.
    • Set does not guarantee the order of elements. Some implementations may have a specific order (e.g., LinkedHashSet, TreeSet), but the Set interface does not require it.
  • Duplicates:

    • List allows storing duplicate elements.
    • Set does not allow duplicates. When attempting to add a duplicate, the operation is either ignored or returns false (depending on the implementation and method).
  • Performance:

    • Add and remove operations in the middle of a List can be slower (especially for ArrayList) than in a Set.
    • Checking for the presence of an element (contains) in hash-based Sets (HashSet) is usually faster (average O(1)) compared to List (average O(n)).
    • Index-based operations (e.g., get, set) are only available in List.
  • Implementations:

    • Common List implementations: ArrayList, LinkedList, Vector.
    • Common Set implementations: HashSet, LinkedHashSet, TreeSet.

Here are examples demonstrating the differences:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CollectionDifferences {

    public static void main(String[] args) {

        // List allows duplicates and maintains order
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Apple"); // Added duplicate
        System.out.println("List: " + list); // Outputs [Apple, Banana, Apple]
        System.out.println("List at index 1: " + list.get(1)); // Access by index

        // Set does not allow duplicates and order is not guaranteed (for HashSet)
        Set<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Apple"); // Attempt to add duplicate - will be ignored
        System.out.println("Set: " + set); // Outputs something like [Apple, Banana] or [Banana, Apple]
        // set.get(1); // Compilation error - no access by index
    }
}

Comparison table:

Characteristic List Set
Order Guaranteed (insertion order) Not guaranteed (for HashSet, TreeSet has sorted order)
Duplicates Allowed Not allowed
Access by index Possible (get(int index)) Not possible
contains() performance O(n) on average (for ArrayList) O(1) on average (for HashSet)
Typical implementations ArrayList, LinkedList, Vector HashSet, LinkedHashSet, TreeSet