Arrays and Arraylists

Arrays and arraylists are data structures that are used to store large collections of data of the same type, in one place. They can be used to replace a large amount of variables. For example, instead of having 100 variables to store 100 different values, you can store them in a single array with the length 100. Both arrays and arraylists are 0-indexed, meaning that their first element can be accessed using the index 0.

Arrays

Arrays are data structures with a fixed or immutable length. This means that once the array is declared with a specified length, this cannot be changed. Arrays can be declared with both primitive data types and objects. If you try to access elements that are not within the array's length, Java will throw an ArrayIndexOutOfBoundsException.


Initialization

Since arrays are objects in Java, they require the keyword new when an empty array is being declared. The value within the second pair of square brackets determines the size or length of the array. Remember that the length of the array is immutable. An array can be initialized in three ways:

                    
    int[] arr = new int[5];

    int arr[] = new int[5];

    int[] arr;
    arr = new int[5];
                

An empty array of numerical primitive data types (e.g. int or double) will be set to 0, an empty boolean array will be set to false, an empty char array will be set to ASCII 000 or \u0000 (null), and empty objects arrays will reference to null.

                    
    int[] intArray = new int[5]; //Will create an array of {0, 0, 0, 0, 0}
    double[] doubleArray = new double[5]; //Will create an array of {0.0, 0.0, 0.0, 0.0, 0.0}
    char[] charArray = new char[5]; //Will create an array of {'', '', '', '', ''}
    boolean[] boolArray = new boolean[5]; //Will create an array of {false, false, false, false, false}
    Integer[] integerArray = new Integer[5]; //Will create an array of (null, null, null, null, null}
                

Arrays can also be initialized using array literals. This can be done with braces and commas.

                    
    int[] arr = {1, 2, 3, 4, 5};
                

Accessing Elements and Traversal

Elements in the array can be accessed by using the name of the array, followed by brackets with the index of the element.

                    
    int[] arr = {3, 10, 8, 2, 4};
    System.out.println(arr[0]); //prints 3
                

The length of an array is a public final field that can be accessed directly from the array.

                    
    int[] arr = {3, 10, 8, 2, 4};
    System.out.println(arr.length); //prints 5
                

This allows for the traversal through the array of an unknown length, and allows the program to modify the elements of the array, using a for loop.

                    
    for(int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " "); //prints the current element
        arr[i]++; //increases the current element by one
    }
                

Another way to traverse an array is to use a for-each loop. This type of loop is used to access the elements within the array when it's not necessary for the elements to be modified. Unlike a standard for loop, a for-each loop does not keep track of the index, and can only iterate forward in single steps.

                    
    int odd = 0;
    for(int num : arr) {
        if(num%2 != 0)
            odd++;
    }
    System.out.println(odd); //prints the number of odd numbers in the array
                

Multi-Dimensional Arrays

Multi-dimensional arrays are very similar to one-dimensional arrays. A two-dimensional array, for example, is simply an array of arrays.


Initialization

Just like a one-dimensional array, a 2D array can be initialized with or without a length, or with an array literal.

                    
    int[][] arr = new int[3][3];
    int arr[][] = new int[3][3];
    int[] arr[] = new int[3][3]; //location of bracket pairs do not matter

    int[][] arr;
    arr = new int[3][3];

    int[][] arr = {{5, 2, 6},
                   {1, 3, 4},
                   {9, 8, 7}};
                

In the last example, we can see that:
arr[0] = {5, 2, 6}
arr[1] = {1, 3, 4}
arr[2] = {9, 8, 7}

For higher dimension arrays, continue the pattern by adding more bracket pairs and/or brace pairs. For example:

                    
    int[][][] arr = new int[3][3][3];
                

Acessing Elements and Traversal

When accessing multi-dimensional arrays, you must specify the index of each dimension. For example, with a 2D array, you must use two sets of brackets with the indices you would like to access.

                    
    int[][] arr = {{5, 2, 6},
                   {1, 3, 4},
                   {9, 8, 7}};
    
    System.out.println(arr[2][1]); //prints 8
                

To traverse a multi-dimensional array, nested loops must be used.

                    
    for(int i = 0; i < arr.length; i++) {
        for(int j = 0; j < arr[i].length; j++) {
            arr[i][j]++; //increases the current element by one
        }
    }

    for(int[] i : arr) {
        for(int j : i) {
            System.out.print(j + " "); //prints the current element
        }
        System.out.println();
    }
                

Arraylists

Simply put, an arraylist is a resizeable array, which means that their length can increase when needed. However, arraylists can only hold objects, not primitive data types. To hold primitive data types, an arraylist of its respective wrapper classes (e.g. Integer instead of int) must be used. Arraylists also belong to the java.util library, meaning that this must be imported to use arraylists.

                    
    import java.util.List;
    import java.util.ArrayList;
    //or
    import java.util.*;
                

Initialization

Just like arrays, arraylists are a class, meaning that they require the keyword new to instantiate. However, unlike arrays, the values of the arraylist cannot be set while initializing. The data type of the arraylist is set using the < > symbols.

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

Methods

Arraylists in Java come with a large amount of methods. These methods allows the user to access and modify the elements within the list. Listed below are some of the more useful arraylist methods. (E represents the data type of the arraylist)

Accessing Elements and Traversal

Arraylist traversal is generally done using a for-each loop, although for loops are also used.

                    
    for(Integer num : list) {
        System.out.print(num + " ");
    }

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