Arrays in Java

An array stores a collection of values (elements) which are all of the same type. The following statement creates an array of integers:

int[] arr = {38, 27, 43, 3, 9, 82, 10};

The array variable arr is of the type int[], where int is the type of the elements. This array is initialized with an initializer list, a list of values delimited by braces {}.

An alternative way of creating an array is using the new operator. The following statement creates an array of length 7; by default, the integer elements are initialized to be 0.

int[] arr = new int[7];

The length field gives the number of elements an array can hold, for example, arr.length. The length of an array is fixed once it is created (either with an initializer list or using the new operator).

Each element is accessed using the array variable name followed by the index of the element. The first element has index 0 (zero-based indexing). The following statements assign values to elements in arr:

arr[0] = 38;
arr[1] = 27;

The index must be greater than or equal to 0 and strictly less than the length of the array. For example, the legal indices for arr are from 0 to arr.length - 1. If we access an array using an index beyond this range, we will get an exception: ArrayIndexOutOfBoundsException

Loops over Arrays

The following code uses a for loop to print out each array element. The index increases from 0 to arr.length - 1.

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

A convenient way to access array elements is the for-each loop. For example,

for (int elem : arr)
  System.out.println(elem);

The colon (:) stands for “in”. Here the variable elem is assigned with each element in arr one by one.

The following is a simple method which compute the average of all values in an array.

public static double average(int[] arr)
{
    int sum = 0;
    for (int elem : arr)
        sum += elem;
    return ((double) sum) / arr.length;
}
public static double average2(int[] arr)
{
    int sum = 0;
    for (int i = 0; i &lt; arr.length; i++)
        sum += arr[i];
    return ((double) sum) / arr.length;
}

Next is a method which creates a new array by concatenating two input arrays.

public static int[] concatenate(int[] a, int[] b)
{
    int[] newArr = new int[a.length + b.length];
    int i = 0;
    for (int elem : a)
        newArr[i++] = elem;
    for (int elem : b)
        newArr[i++] = elem;
    return newArr;
}

Note that we create the new array newArr with a specific length before filling up the values. The length of an array is fixed once created.

The following example defines a method minValue() which finds the minimum value in an array of integers.

public static int minValue(int[] arr)
{
    int min = arr[0];
    for (int elem : arr)
    {
        if (elem < min)
            min = elem;
    }
    return min;
}
public static int minValue2(int[] arr)
{
    int min = arr[0];
    for (int i = 1; i < arr.length; i++)
    {
        if (arr[i] < min)
            min = arr[i];
    }
    return min;
}

The variable min keeps the current minimum values as the loop scans through every element in the array.

Sometimes we may wish to find the index of an array element instead of its value; given an index we can easily find the corresponding value by accessing the array, but given a specific value, it is not easy to know where it comes from. The following code defines a method minIndex() which finds the index of the minimum value in an array.

public static int minIndex(int[] arr)
{
    int index = 0, min = arr[0];
    for (int i = 1; i < arr.length; i++)
    {
        if (arr[i] < min)
        {
            min = arr[i];
            index = i;
        }
    }
    return index;
}

Arrays Are Objects

An object variable is only a reference to an object. The following code declares two array variables arr and c. The variable c points to the same array object as arr. This means, arr[0] and c[0] are referring to the same memory location. Thus, at the end, arr[0] has value 39.

int[] arr = {38, 27, 43, 3, 9, 82, 10};
int[] c = arr;
c[0]++;       // arr[0] == ?

When an object variable is passed as a parameter to a method, it still refers to the original object. The following is a method increase() which takes two parameters: an array and an integer.

public static int increase(int[] x, int y)
{
    x[0]++;
    y++;
    return y;
}
public static void main(String[] args)
{
    int[] arr = {38, 27, 43, 3, 9, 82, 10};
    int b = 1;
    int ret = increase(arr, b);
    // arr[0] == ???, b == ???
}

In the main() function, it calls increase() by passing two parameters. After the call returns, the value of arr[0] will be changed to 39, since arr is a reference to the array object; the variable x in increase() points to the same array. Whereas, the value of b is still 1 since the local copy y does not affect b.

The following example is another method which swaps two elements in an array.

public static boolean swap(int[] arr, int i, int j)
{
    if (i < 0 || i >= arr.length ||
        j < 0 || j >= arr.length)
        return false;

    int tmp = arr[i];     // swap arr[i] with arr[j]
    arr[i] = arr[j];
    arr[j] = tmp;
    return true;
}

This method takes an array and two indices as parameters, and swaps the values at the two indices. It first verifies that the two indices are valid; then it makes a swap between the elements at the two indices. When the function returns (and the indices are both valid), the content of the array will be changed.

boolean ret = swap(arr, 1, 3);

Arrays of Objects

Array elements can also be object references. The following example creates an array of Strings.

String[] names = new String[5];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Carl";

When the array is initially allocated by the new operator, it holds null reference. The null value means the object reference points to nothing (not initialized).

Command-line arguments of a program are stored in an array of Strings. The following class will simply print out all command-line arguments line by line.

public class CommandLine
{
    public static void main(String[] args)
    {
        for (int i = 0; i < args.length; i++)
            System.out.println(args[i]);
        // for (String arg : args)
        // System.out.println(arg);
    }
}

When we type in the following command to run the program, the arguments are stored in an array of Strings and passed to the main() function. Note that the quoted part will be one String.

$java CommandLine aa bbb "cc ddd" e

Two Dimensional Arrays

A two-dimensional array can be defined by specifying each dimension:

int[][] matrix = { 
            {11, 12, 13}, 
            {21, 22, 23} 
        };

Each element is referenced using two indices, for example:

matrix[0][1] = 12;

Each row in the two dimensional array can be specified using one index

int[] arr = matrix[0];

The rows in a two-dimensional array may be initialized with different length (called ragged array). The following example creates such an array and prints out the elements row by row.

int[][] arr = { {11, 12, 13},
                {21, 22, 23, 24},
                {31, 32} };
for (int i = 0; i < arr.length; i++)
{
    for (int j = 0; j < arr[i].length; j++)
        System.out.print(arr[i][j] + " ");
    System.out.println();
}

We can use the new operator to create an array. Note that in this case each row has the same length N.

double[][] a = new double[M][N];

java.util.Arrays

The class java.util.Arrays contains various methods for manipulating arrays. We have several examples below:

int[] arr = {38, 27, 43, 3, 9, 82, 10};

// Convert to a well-formated string
String str = Arrays.toString(arr);
Arrays.sort(arr);       // Sort the array
Arrays.fill(arr, 111);  // Assign a value to each element
// Make a copy
int[] arr2 = Arrays.copyOf(arr, arr.length);
Arrays.equals(arr, arr2); // Check all elements are the same

Document on java.util.Arrays:
http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

In the class java.lang.Math, the method random() returns a random double value between 0.0 and 1.0. The following method generates a random array of integers with a specific length.

public static int[] randArray(int length, int max)
{
    int[] arr = new int[length];
    for (int i = 0; i < length; i++)
        arr[i] = (int) (Math.random() * max);
    return arr;
}

Note that random() returns a double value greater than or equal to 0.0 and less than 1.0. So the integer generated above is greater than or equal to 0 but strictly less than max.

Document on the method random() in java.lang.Math:
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html#random()

Comments

comments

Tagged with: , ,
Posted in Java