Video in progress
What is the difference between a plain array and an ArrayList?
An array's length is fixed at creation, and it can store primitives directly. An ArrayList grows on its own and has convenient methods, but it only holds objects (Integer, not int).
📖 Answer
int[] arr = new int[3]; // the length is always 3
arr[0] = 10;
List<Integer> list = new ArrayList<>();
list.add(10); // grows by itself when needed
list.add(20);
The main differences:
- length:
arr.lengthnever changes,list.size()does; - type:
int[]stores primitives, whileArrayList<Integer>boxes them, so every element is a separate object; - API:
ArrayListhascontains,remove,indexOfandstream(), while for an array you need theArraysutility; - generics: arrays are covariant (
String[]is anObject[]), butList<String>is not aList<Object>.
With large amounts of numbers (say, a million ints) an array takes several times less memory. In ordinary business code, though, List is more convenient.
Sign up to mark studied questions and save your progress.