Arrays & ArrayLists

Arrays & ArrayLists

So far we’ve talked about numbers, strings and Booleans where each variable just stores one thing at a time. What happens if we want to manage a shopping list, or a list of students in my class… and we want to be able to manage that entire list of things together? Java allows us to do this by creating arrays. So instead of creating variables student1, student2, student3, etc, we can have one variable called students and use that in our code.

There are two main types of arrays in Java. The classic static array has a size that is fixed at declaration. Once the memory space has been allocated, they can not be resized. The other type is known as ArrayLists and are a dynamically resizable construct available when the size of the array is not known in advance.

We’ll start by looking at the static array.

Array: Declaration

Method 1

    int[] primes = new int[10];
    primes[0] = 1;
    primes[1] = 2;
    primes[2] = 3;
    primes[3] = 5;
    primes[4] = 7;
    primes[5] = 11;
    primes[6] = 13;
    primes[7] = 17;
    primes[8] = 19;
    primes[9] = 23;

Method 2

    int[] primes = {1,2,3,5,7,11,13,17,19,23};

Arrays of objects

What happens when the objects in your array require you to provide parameters to the constructor? You declare the array, and then instantiate each individual element. Here is an example of the technique.

    Student[] students = new Student[10];
    students[0] = new Student("Miko", "Lausanne", "Diploma", 12, 40000);
    students[1] = new Student("Tiago", "Lausanne", "Diploma", 12, 40000);
    students[2] = new Student("Paolo", "Lausanne", "Diploma", 12, 40000);
    students[3] = new Student("Bora", "Lausanne", "Diploma", 12, 40000);
    students[4] = new Student("Ozan", "Lausanne", "Diploma", 12, 40000);
    students[5] = new Student("Alessio", "Lausanne", "Diploma", 12, 40000);
    students[6] = new Student("Inigo", "Lausanne", "Diploma", 12, 40000);
    students[7] = new Student("Apostolos", "Lausanne", "Diploma", 12, 40000);
    students[8] = new Student("Daniel", "Lausanne", "Diploma", 12, 40000);
    students[9] = new Student("Misha", "Lausanne", "Diploma", 12, 40000);

    for (Student individualStudent : students) {
        System.out.println(individualStudent);
    }

Array: Iteratation

There is a special “for loop” for iterating through an array. The following two loops produce the same output.

for (int item : primes) {
   System.out.println( item );
}

for (int i=0; i<primes.length; i++) {
   System.out.println( primes[i] );
}

Array: Functions and properties

Requires import java.util.Arrays;

// Check if two arrays are filled with matching values
if ( Arrays.equals( primes, other )) {
    System.out.println("The two arrays match");
}

// Length of an array
int l = primes.length;

// Sort an array in ascending order
Arrays.sort( primes );

// Create a string listing the contents of the array
// output: [1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
System.out.println( Arrays.toString( primes ));

ArrayList: Declaration

When instantiating an ArrayList, you can nominate the datatype to be contained by the array list or leave it unspecified (to allow for a potential mix of different data types). There is an example of each below.

ArrayLists require: import java.util.ArrayList;

Example 1: Create an ArrayList specifying elements to be String

ArrayList<String> alist = new ArrayList<String>();
alist.add("first");
alist.add("second");

for (String item: list) {
    System.out.println( item );
}

Example 2: Create an ArrayList without specifying element type

ArrayList list = new ArrayList();
list.add( 3.14) );                      // Add a float
list.add( true );                       // Add a boolean
list.add( "Mixed data arrayList" );     // Add a string
list.add( 99 );                         // Add an integer

for (Object o : list) {
    if (o.getClass() == String.class) {
        System.out.println("The item is a string and it's value was "+o);
    } else if (o.getClass() == Integer.class) {
        System.out.println("The item is an integer and it's value was "+o);
    } else if (o.getClass() == Float.class) {
        System.out.println("The item is a float and it's value was "+o);
    } else if (o.getClass() == Boolean.class) {
        System.out.println("The item is a boolean and it's value was "+o);
    }
}

ArrayList: Methods

ArrayList: Convert to/from arrays

As arrays and ArrayLists both have beneifts over the other, the chances are high you are going to want to convert from one to the other at some time or another.

Array to ArrayList

int[] a = {1,2,3,5,7,11,13,17,19,23};
ArrayList alist = new ArrayList<>(Arrays.asList(a))

ArrayList to Array

String[] a = (String[])alist.toArray(new String[alist.size()]);
// or
int[] a = (int[])alist.toArray(new int[alist.size()]);

Two dimensional array

It is possible to create a two dimensional static array.

int [][] a = {
   { 1,  2,  3,  4,  5 },
   { 11, 12, 13, 14, 15 },
   { 21, 22, 23, 24, 25 }
};
System.out.println( a[i][j] );

Two dimensional array where values are not pre-known

int [][] a = new int[3][5];

To iterate over the 2D array

for (int[] row : a ) {
    for (int cell : row) {
        System.out.println( cell );
    }
}

Exercises: Arrays and ArrayLists

Codingbat.com, Array-1 and Array-2