CMPS 144
Introduction to the ArrayList and Comparison with Arrays

Instances of the java.util.ArrayList class are similar to arrays but provide more flexibility/convenience.

Similarities

Both (one-dimensional) arrays and ArrayLists are for the purpose of storing and manipulating (linear) lists of elements "indexed by" a consecutive range of natural numbers, starting at zero. That is, an element in such a list is referred by its position within that list.

Both arrays and ArrayLists can be "iterated over" using Java's for-each loop. The examples below illustrate its use. On successive iterations of the loop, the variable num assumes the values of the elements indexed by 0, 1, 2, etc.

/* Returns the sum of the elements
** of the given array.
*/
public static int sumOf(int[] ary) {
   int sumSoFar = 0;
   for (int num : ary) {
      sumSoFar = sumSoFar + num;
   }
   return sumSoFar;
} 
/* Returns the sum of the elements
** of the given ArrayList.
*/
public static int sumOf(ArrayList<Integer> aryList) {
   int sumSoFar = 0;
   for (Integer num : aryList) {
      sumSoFar = sumSoFar + num;
   }
   return sumSoFar;
}

Differences


Summary of Fundamental Operations on ArrayLists

Method CallEffect
size() Returns the number of occupying elements
get(k) Returns (reference to) the element at position k
set(k,E) Replaces the item at position k by E.
add(k,E) Inserts E at position k, shifting elements numbered k and higher upward
add(E) Inserts E at position size()
remove(k) Removes the element at position k, shifting elements numbered k+1 and higher downward

Footnotes

[1] The default value for all reference (i.e., non-primitive) types is null. For primitive numeric types (including int and double), the default value is zero. For boolean, it is false. For char, it is the character represented by the number zero, which as a literal in Java is written '\0' and is usually referred to as the null character.

[2] The array abstraction has been included in almost every widely used programming language, going back to FORTRAN in the late 1950's. With some minor variations, the same syntax has been used, too. In Java, that syntax seems out of place, but the designers of Java adopted it, probably to appeal to experienced programmers who were familiar with it.