List and Set
Collection Hierarchy (excerpt)
plaintext
Iterable
└── Collection
├── List — ordered, allows duplicates
├── Set — no duplicates
└── Queue
List
A List maintains insertion order and allows duplicates and null values (in mutable implementations).
Common Implementations
| Class |
Backed by |
Access |
Insert/Delete mid |
ArrayList |
Array |
O(1) |
O(n) |
LinkedList |
Doubly-linked list |
O(n) |
O(1) at known node |
Creating Lists
java
List<String> mutable = new ArrayList<>();
mutable.add("Alice");
mutable.add("Bob");
List<String> fixed = List.of("Alice", "Bob", "Carol");
List<String> copy = new ArrayList<>(List.of("A", "B", "C"));
Key List Methods
java
List<String> list = new ArrayList<>(List.of("A", "B", "C", "B"));
list.get(1);
list.set(0, "Z");
list.add(1, "X");
list.remove(0);
list.remove("B");
list.indexOf("B");
list.lastIndexOf("B");
list.subList(1, 3);
list.size();
list.contains("C");
list.isEmpty();
Collections.sort(list);
Set
A Set contains no duplicates. Most implementations do not guarantee order.
Common Implementations
| Class |
Order |
Null |
Performance |
HashSet |
None |
One null allowed |
O(1) avg |
LinkedHashSet |
Insertion order |
One null allowed |
O(1) avg |
TreeSet |
Natural / Comparator |
No null |
O(log n) |
Creating Sets
java
Set<String> mutable = new HashSet<>();
mutable.add("Alice");
mutable.add("Alice");
System.out.println(mutable.size());
Set<String> fixed = Set.of("Alice", "Bob", "Carol");
Key Set Methods
java
Set<Integer> set = new HashSet<>(Set.of(1, 2, 3, 4, 5));
set.add(6);
set.add(3);
set.remove(2);
set.contains(4);
set.size();
Set<Integer> other = new HashSet<>(Set.of(3, 4, 5, 6, 7));
set.retainAll(other);
set.addAll(other);
set.removeAll(other);
List.of() and Set.of() — Important Restrictions
| Restriction |
Detail |
| Unmodifiable |
add, remove, set throw UnsupportedOperationException |
No null elements |
Throws NullPointerException |
Set.of() no duplicates |
Throws IllegalArgumentException at creation |
| Iteration order |
Not guaranteed (especially Set.of()) |
Choosing List vs Set
Use List when |
Use Set when |
| Order matters |
Uniqueness is the constraint |
| Duplicates allowed |
Fast membership test (contains) |
| Index-based access needed |
No index access needed |