ArrayListsStudents easily confuse the two. The tradeoffs between them is worth noting.
| Arrays | ArrayLists | |
|---|---|---|
| Subscripting operator for access is convenient | Only access is through instance methods | |
| Length cannot be changed once created | Grows and shrinks with additions and subtractions | |
| (Fast performance due to primitive implementation) | (Slower performance due to method call overhead) |
A comparison via simple example:
| Array | ArrayList | |
|---|---|---|
String[] students = new String[4];
students[0] = "John";
students[1] = "Paul";
students[2] = "George";
students[3] = "Ringo";
for(int i = 0; i < students.length; i++) {
System.out.println(students[i]);
}
|
ArrayList students = new ArrayList();
students.add("John");
students.add("Paul");
students.add("George");
students.add("Ringo");
for(int i = 0; i < students.size(); i++) {
String name = (String) students.get(i);
System.out.println(name);
}
|
As reference, an ArrayList has the following methods.
int size() |
Returns the number of elements in this list. |
boolean add(Object value) |
Appends value onto list's end, returning
true. |
void get(int index) |
Returns value at index within list. |
Object set(int index, Object value) |
Changes value at index to
value, returning previous value there. |
Object remove(int index) |
Removes value at index, shifting elements
above beyond it forward one place over it. |
void add(int index, Object value) |
Adds value at index, shifting elements
there and beyond back one place to make room. |