Sub topic 1
What the Collections Framework Is
The Big Idea
A collection is an object that holds a group of other objects. The Java Collections Framework is the set of ready-made collection types that comes with Java. It saves you from writing your own lists and lookup tables.
The framework has three main interfaces. An interface is a list of methods that a class promises to provide.
| Interface | What it holds | Example class |
|---|---|---|
| List | Items in order, duplicates allowed | ArrayList |
| Set | Unique items only | HashSet |
| Map | Key-value pairs | HashMap |
Typed Collections with Generics
A generic type parameter is the type in angle brackets, such as <String>. It tells Java what the collection may hold. Java then stops you from adding the wrong type.
The diamond operator <> on the right side lets Java fill in the type for you:
List<String> names = new ArrayList<>();Ordered Sequences with List and ArrayList
An ArrayList is a list that grows as you add items. Each item has an index, which is its position counted from 0.
import java.util.ArrayList;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
names.add("Ana");
System.out.println(names); // [Ana, Ben, Ana]
System.out.println(names.get(1)); // Ben
names.set(1, "Cara");
System.out.println(names); // [Ana, Cara, Ana]
System.out.println(names.size()); // 3
for (String n : names) {
System.out.println(n);
}
}
}The loop at the end is a for-each loop. It visits each item once, in order.
Storing Numbers: Wrapper Types and Autoboxing
Collections hold objects, not primitives like int. A wrapper type is the object version of a primitive. For example, Integer wraps int. Autoboxing means Java converts between the two for you.
import java.util.ArrayList;
import java.util.List;
public class BoxingDemo {
public static void main(String[] args) {
List<Integer> nums = new ArrayList<>(List.of(10, 20, 30));
nums.remove(1); // removes the element at index 1
System.out.println(nums); // [10, 30]
nums.remove(Integer.valueOf(10)); // removes the value 10
System.out.println(nums); // [30]
}
}Exercise
You have a List<Integer> holding [5, 1, 7]. What does the list contain after calling remove(1)?
Show answer
[5, 7]. The call removes the item at index 1, which is the number 1. To remove the value 7 instead, call remove(Integer.valueOf(7)).
Exercise
Why do you write List<Integer> and not List<int>?
Show answer
Collections can only hold objects. Integer is the wrapper object for int, and autoboxing converts between them for you.