What is the difference between an array and an ArrayList in Java?
An array is a fixed length block of values that the language itself provides. An ArrayList is a class in the standard library that keeps an array inside it and grows it when it needs to.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
// An array has a fixed length and holds any type of value.
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
// An ArrayList grows, and it only holds objects.
List<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
System.out.println("array length : " + numbers.length);
System.out.println("list size : " + list.size());
System.out.println("list third : " + list.get(2));
try {
numbers[3] = 99;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("array index 3 : out of bounds");
}
}
}
There are four differences that matter in practice.
The first one is the length. An array never changes its length. An ArrayList grows as you add to it and can be made shorter as you remove from it.
The second one is what they can hold. An array can hold primitive values directly, so an int[] stores real numbers with no overhead. An ArrayList can only hold objects, so a list of numbers is really a list of boxed Integer objects.
The third one is the methods. An array gives you the length and nothing else. An ArrayList gives you add, remove, contains, indexOf and the rest of the collection methods.
The fourth one is speed. An array is a plain block of memory, so it is faster and it uses less memory. That difference is real but it is small, and it only matters in code that is genuinely doing a lot of work.
The next question in this topic looks at how to choose between them.