You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Arrays are powerful but fixed in size. Java's Collections Framework provides dynamic, resizable data structures — lists, sets, maps, and queues. Generics add type safety so collections only hold the types you specify.
Iterable
└── Collection
├── List (ordered, allows duplicates)
├── Set (no duplicates)
└── Queue (FIFO ordering)
Map (key-value pairs — separate hierarchy)
A List is an ordered collection that allows duplicates.
import java.util.ArrayList;
import java.util.List;
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // duplicates allowed
System.out.println(names); // [Alice, Bob, Alice]
System.out.println(names.get(0)); // Alice
System.out.println(names.size()); // 3
names.remove("Alice"); // removes first occurrence
System.out.println(names); // [Bob, Alice]
| Method | Description |
|---|---|
add(element) | Appends to the end |
add(index, element) | Inserts at the specified index |
get(index) | Returns element at index |
set(index, element) | Replaces element at index |
remove(index) or remove(object) | Removes an element |
size() | Number of elements |
contains(object) | Check if element exists |
indexOf(object) | First index of element (-1 if not found) |
isEmpty() | True if no elements |
sort(comparator) | Sorts the list |
| Feature | ArrayList | LinkedList |
|---|---|---|
| Backed by | Resizable array | Doubly linked list |
| Random access | O(1) — fast | O(n) — slow |
| Insert/delete at ends | O(1) amortized | O(1) |
| Insert/delete in middle | O(n) | O(1) if you have the node |
| Best for | Most use cases | Frequent insertions/deletions |
Tip: Use
ArrayListby default. Switch toLinkedListonly if profiling shows it is faster for your specific workload.
A Set contains no duplicate elements.
import java.util.HashSet;
import java.util.Set;
Set<String> colours = new HashSet<>();
colours.add("Red");
colours.add("Green");
colours.add("Red"); // ignored — already exists
System.out.println(colours); // [Red, Green] (order not guaranteed)
System.out.println(colours.size()); // 2
| Implementation | Ordering | Null allowed? | Performance |
|---|---|---|---|
HashSet | No order | Yes (one null) | O(1) add/remove/contains |
LinkedHashSet | Insertion order | Yes (one null) | O(1) with ordering overhead |
TreeSet | Sorted (natural or custom) | No | O(log n) |
A Map stores key-value pairs. Keys are unique.
import java.util.HashMap;
import java.util.Map;
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.