Arrays and ArrayLists

June 7, 2020 Java 12 min

Arrays

Arrays are one of the most important data structures in programming of any kind. In Java, they allow one to store many objects in a single variable, indexed using an unsigned integer always starting at 0 and progressing to one less than the number of elements in the array.1

One example of where an array would be useful is handling the students that are present within a classroom.

Creating an array


Declaration

The syntax for declaring an array in Java is quite simple:

type[] name;

This declares an array of type type and name name. The [] are used to define that this is a 1 dimensional array. For an example of declaring an integer array called numbers, we can do the following:

int[] numbers;

While the above syntax is considered best practice, the following is also allowed but discouraged2:

int numbers[];

Initialization

Once an array is declared, it must be initialized to access the values within it. There are many different ways to initialize in array, with some providing values and other not. The simplest initialization can be performed with the new operator.

name = new type[length];

Keep in mind that the declared type must match the initialized one. The length of the array is the exact number of elements that the array will have and can be any non-negative integer.

This form will initialize the array with the specified length and will populate its elements based on the default value for every element. Below is a list of the default values for every primitive type.3

Type Default Value
byte (byte) 0
short (short) 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean false

For all other reference types, where the type of an array isn't a primitive like the ones stated above, the default value is null. One can also note that all of these values are the representative 0 value of that type in memory.

Alternatively, if one doesn't want to use the default values above, a different syntax is provided to define the default values.

name = new type[length] {value1, value2, ... valueN};

In this case, the length must match the number of values provided, or it can be completely omitted. new type[length] can actually be completely omitted. For some examples of initializing arrays, let's initialize the numbers array with the 3 values 4, 6, and 2.

numbers = new int[3] {4, 6, 2};
numbers = new int[] {4, 6, 2};
numbers = {4, 6, 2};

All of the above will produce the same result.

Using an array


Accessing Elements

Now that we have an array with some values in it, let's take a look at how to access these values. The general syntax for accessing an element in an array arr is with arr[n] where n is the index of the element you are trying to access. Once again, keep in mind that this index start at 0. To see this in action, let's have a program print out the values in our numbers array.

for (int i = 0; i < numbers.length; i ++) {
    System.out.print(numbers[i] + " ");
}

This program will output: 4 6 2.

Trying to access an index that doesn't exist, such as numbers[4] will raise an ArrayIndexOutOfBounds exception.

Modifying Values

To change the value of an element in the array, the same syntax as accessing that element is used, except one assigns to it using the = operator (or any derivative such as +=, -=, etc.). So, to change the second element in the numbers array to 3, we can run:

numbers[2] = 3;

Then, running the example code in the previous section would output: 4 3 2.

Changing Size

Arrays cannot be changed in size after initialization. The only option to increase the size of an array is to create a new array of a different size and copy over the elements, either through a method like Arrays.copyTo or a simple for loop. If changing the size of your array is something that is often required in your program, continue reading to learn how to use a Java ArrayList.

Multi-dimensional Arrays

While all of the above explained a one dimensional array, everything applies to multi-dimensional arrays. For example, to create, set values in, and access a two dimensional (2D) array, the following can be done:

int[][] arr = {{1, 2, 3}, {2, 3, 1}, {3, 2, 1}}
for (int x = 0; x < arr.length; x ++) {
    for (int y = 0; y < arr[x].length; y++) {
        arr[x][y] = 1 - arr[x][y];
    }
}

As you can see with the names x and y, it is often helpful to think of multidimensional arrays as grids or planes with the x and y coordinates corresponding to the cells in the grid or the intersecting axis of a plane. After running this code, the arr array would contain the values:

+0 -1 -2
-1 -2 +0
-2 -1 +0

All of these concepts can then be extended to multi-dimensional arrays of any number of dimensions.


ArrayLists

While arrays are great, they (intentionally) lack the capability of changing their size. An ArrayList on the other hand allows simple changes in size, abstracting away the normal logic required for changing the sizes of an array. They are commonly used in implementations where an unknown or variable number of objects need to be stored, accessed, or processed.

Creating an ArrayList


Declaration

The general syntax for declaring an ArrayList is as follows:

ArrayList<Type> name;

This declares an ArrayList of type Type and name name. Keep in mind that Type cannot be a primitive type (byte, short, int, long, float, double, char, or boolean), instead having to use the corresponding object wrapper classes (Byte, Short, Integer, Long, Float, Double, Character, or Boolean). This does not affect future assignment of access because of Java's autoboxing and unboxing.4

Initialization

Initializing an ArrayList in Java follows a similar style to declaration and doesn't have multiple versions like those for an array. To initialize an ArrayList with a name name and a type Type, the following format is used:

name = new ArrayList<Type>(capacity);

The capacity parameter is completely optional and only serves as a way to increase efficiency of the internal operations. The way an ArrayList works internally is by storing an array with a size of capacity (10 by default) and keeping track of the last used element. If a user tries to add an extra element, the capacity of the ArrayList (and length of the internal array) is doubled. Thus, setting a capacity serves as a way to prevent these inevitable changes in size that use up a lot of processing power.

For future examples, let's create an ArrayList called numbers that will hold integers.

ArrayList<Integer> numbers = new ArrayList<Integer>();

Using an ArrayList


Modifying Values

Now that we have an ArrayList numbers, let's add some values to it. To add elements to an ArrayList, one can do the following:

numbers.add(3);
numbers.add(2);

This will add the integers 3 and 2 to the numbers ArrayList.

One can also insert elements into an ArrayList using the following sytax:

arrayList.insert(index, element);

So to insert the number 1 in between 3 and 2, we can run:

numbers.insert(1, 1);

Accessing Elements

To get elements in an ArrayList, one can use a similar syntax to that of Arrays, except by calling a method instead of using the [] notation:

arrayList.get(index);

This will return the value at index index of the ArrayList arrayList. Let's demonstrate this by printing the values of the numbers ArrayList.

for (int i = 0; i < numbers.size(); i ++) {
    System.out.print(numbers.get(i) + " ");
}

This code will output: 3 1 2.

Because an ArrayList implements the Iterable interface, one can also loop through the elements using the for ( : ) syntax as follows:

for (int number : numbers) {
    System.out.print(numbers + " ");
}

The output of this program will be identical to the previous one.

Removing Elements

Finally, to remove elements from an ArrayList, another method called remove() is used. It can be called in either of the following ways:

arrayList.remove(index);
arrayList.remove(object);

This will either remove the object at index index in ArrayList arrayList, or find and remove the object object in the ArrayList arrayList. As an example, let's remove the 3 from our numbers ArrayList:

numbers.remove(0);

Now, running the output code from before will output: 1 2.


  1. This is called 0-indexed. Some other languages have arrays start at index 1.

  2. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

  3. https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.12.5

  4. Read more here.