Arrays vs collections
Know when a plain array is enough, and what a List buys you for its extra weight.
Open this lesson in the learning hubKey points
- An array has a length fixed at creation. A
Listgrows and shrinks for you, which is why it is the default. - Arrays store primitives directly, so
int[]never boxes. AList<Integer>wraps every element in an object. - Printing an array shows a hash and
equalscompares identity. Use theArrayshelpers instead. - Arrays are covariant, so
Object[] o = new String[2]; o[0] = 42;compiles and then throws at runtime. - Generics are invariant, so the same mistake is a compile error instead. That safety is the whole point.
- Rule of thumb: fixed-size numeric data in a hot loop, use an array. Everything else, use a collection.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] arr = {"a", "b", "c"};
System.out.println("array length : " + arr.length + " (fixed forever)");
System.out.println("array toString : " + Arrays.toString(arr) + " (arr.toString() is a hash)");
System.out.println("arr.equals(copy) : " + arr.equals(new String[]{"a", "b", "c"}));
System.out.println("Arrays.equals : " + Arrays.equals(arr, new String[]{"a", "b", "c"}));
List<String> list = new ArrayList<>(Arrays.asList(arr));
list.add("d");
System.out.println("list grew : " + list + " size " + list.size());
System.out.println("list.equals(copy) : " + list.equals(List.of("a", "b", "c", "d")));
Object[] objs = new String[2];
try {
objs[0] = 42;
} catch (ArrayStoreException e) {
System.out.println("array covariance : ArrayStoreException, found at runtime");
}
System.out.println("generics : invariant, so the compiler catches it instead");
int[] prims = new int[3];
System.out.println("int[] default : " + Arrays.toString(prims) + " (no boxing at all)");
}
}
An array is a memory layout, a collection is an API. Reach for the API unless you measured a reason not to.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.