Array vs ArrayList
Arrays and ArrayLists are very similar.
* In fact, an ArrayList contains an array for storing elements.
* We say the ArrayList is backed by an array.
* ArrayList's main job is to manage the internal array so we don't have to.
The table below compares array operations to ArrayList operations.
iis an integer indexarris an arraylistis anArrayList
| Op | Array | ArrayList |
|---|---|---|
| Size | .length |
.size() |
| Write | arr[i] = obj |
list.add(obj) |
list.set(i, obj) |
||
| Read | obj = arr[i] |
obj = list.get(i) |
Enhanced for Loops and ArrayList¶
An array and an ArrayList can be used in an enhanced for loop (or foreach loop), and the syntax is exactly the same.
String[] sArr = {"A", "B", "C", "D"};
for (String string : sArr) {
// ...
}
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
for (String string : list) {
// ...
}
Practice Exercise¶
One advantage of using an array over
ArrayListis, reading an array element with[]is marginally faster than usingArrayList'sgetmethod.This is because the method call adds an extra step.
String s = sArr[0]; // assignment String st = list.get(0); // method call + assignmentAlso, an array will usually consume less memory.
Still, the ability of an
ArrayListto grow dynamically outweighs this advantage.