Sobes.tech
Junior

What is the difference between List and Set in Java?

sobes.tech AI

Answer from AI

Main differences:

  1. Order of elements:
    • List preserves the order of insertion.
    • Set does not guarantee the order of elements (depends on the specific implementation, for example, LinkedHashSet preserves insertion order).
  2. Duplicates:
    • List allows storing duplicate elements.
    • Set stores only unique elements.
  3. Access to elements:
    • List provides access to elements by index.
    • Set does not provide direct access to elements by index, access is through an iterator or iteration.
  4. Performance:
    • Search and add operations in List with a large number of elements can be slower than in Set (for example, in HashSet).
    • Add and remove operations in Set (for example, HashSet) usually have average constant time complexity.

Example:

// List storing duplicates and preserving order
List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple");
System.out.println(list); // Output: [Apple, Banana, Apple]

// Set storing only unique elements
Set<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple");
System.out.println(set); // Output: [Apple, Banana] (order may vary)

Comparison table:

Aspect List Set
Order Preserved Not guaranteed (depends on implementation)
Duplicates Allowed Not allowed
Access by index Yes No
Interface java.util.List java.util.Set
Typical use Ordered collections, lists Unique collections, sets