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.length never changes, list.size() does;
  • type: int[] stores primitives, while ArrayList<Integer> boxes them, so every element is a separate object;
  • API: ArrayList has contains, remove, indexOf and stream(), while for an array you need the Arrays utility;
  • generics: arrays are covariant (String[] is an Object[]), but List<String> is not a List<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.