Java provides different collections. An array has a fixed size. A List represents ordering. A Set prevents duplicate values. A Map associates values with keys. Generics such as List<String> let the compiler determine the permitted element type.
01Create a mutable list
ArrayList permits add. In contrast, List.of creates an unmodifiable list. Interface and implementation names can differ: List describes the contract and ArrayList the concrete storage.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ada", "Lin"));
names.add("Ada");
var unique = new HashSet<>(names);
Map<String, String> mapping = Map.of("recipient", "fullName");
System.out.println(names.size());
System.out.println(unique.size());
System.out.println(mapping.get("recipient"));
}
}
Run / check
java Main.java02Understand duplicates and keys
HashSet removes duplicate names but does not promise sorted ordering. Map.of maps PDF field names to CSV columns. get returns null for an unknown key.
03Distinguish types and mutability
A final variable only prevents reassignment. It does not make an ArrayList immutable. List.copyOf creates an unmodifiable copy. Even that copy does not automatically deep-copy contained objects.
3 names, 2 unique names and the mapping fullName
Your exercise
Create an unmodifiable copy of the names and then attempt add.
Show the solution and explanation
List<String> snapshot = List.copyOf(names) creates the copy. snapshot.add("Sam") throws UnsupportedOperationException. The original ArrayList can still be modified.
Project context and sources
The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.