Java Arrays

Java arrays are a lot like C/C++ arrays.

The main difference is that Java arrays are objects, in the same way that instances of classes are objects. As with all objects in Java, instances of array are accessed through references. Thus, an array variable in Java is not the actual array: it is just a memory location in which a reference to an array may be stored.

Consider the following code:

int[] heaps;                 // (1)
heaps = new int[6];          // (2)

Line (1) creates a variable called heaps whose type is int[], meaning “array of int”. Because array variables store a reference to an array, and not the array itself, the variable does not point to any actual array yet.

Line (2) creates an array object for storing 6 int elements, and assigns the reference to the newly-created array to the variable heaps. Here’s a picture:

image

Like arrays in C and C++, Java arrays are indexed starting at 0. So, the valid range of indices for this array is 0..5.

Because arrays are accessed through references, it is possible to have two array variables storing references to the same array object. For example:

int[] a;
int[] b;

a = new int[4];
b = a;

a[0] = 15;

// (1)

System.out.println(b[0]); // prints 15

a[0] = 16;

// (2)

System.out.println(b[0]); // prints 16

As a picture, here’s what’s happening at point (1):

image

Here’s what’s happening at point (2):

image

Array length

One nice feature of Java that is not present in C and C++ is the ability to determine the exact number of elements in an array. If arr is an array, then

arr.length

is the number of elements in the array.

For example, the following static method will compute the sum of the elements of any array of int values:

public static int sum(int[] arr) {
  int sum = 0;

  for (i = 0; i < arr.length; i++) {
    sum += arr[i];
  }

  return sum;
}

Default values

When an array object is created using the new operator, each element of the array is automatically initialized with a default value. The default value is 0 for all numeric element types, and the special null reference for all class and array element types.

Here’s a code snippet that illustrates the default value for an array of int values:

int[] t = new int[4];
System.out.println(t[0]);  // guaranteed to print 0

Arrays of references

When an array has a class or array type as its element type, it stores references. In this way, array elements are the same as any other kind of variable.

For example:

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

// (1)

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

Here’s what things look like at point (1):

image

Quick Introduction to ArrayList

A common concern in Java programs is keeping track of collections of objects. Container classes, also known as collections, assist with this task: they allow your program to store collections of objects and then retrieve references to those objects when they are needed.

ArrayList (in the java.util package) is one of the simplest and most useful container classes. An ArrayList object works much like an array, but unlike an array, it has no fixed size, and expands as needed to store however many objects the program requires.

For example, let’s say that you’re writing a program to keep track of your friends’ email addresses. You could represent the email addresses as strings, and use an ArrayList to store them:

ArrayList<String> emailList = new ArrayList<String>();

Note that when declaring an ArrayList variable or creating a new ArrayList object, you must specify what type of objects the array list with contain. This type is called the element type.

To add strings to the list, call the add method:

emailList.add("[email protected]");
emailList.add("[email protected]");
emailList.add("[email protected]");

Each object added to the list is appended onto the end of the sequence of objects.

The size method returns an integer value specifying the number of objects currently in the list. The get method allows you to retrieve the object at a specified index, where 0 is the first object in the sequence, 1 is the second object, etc:

// print all email addresses
for (int i = 0; i < emailList.size(); i++) {
    String email = emailList.get(i);
    System.out.println(email);
}

The set method takes an integer index and a reference to an object, and replaces the object at that index with the specified object. For example, if Jane Smith changes her email address, we could update our list as follows:

String oldEmail = "[email protected]";
String newEmail = "[email protected]";
for (int i = 0; i < emailList.size(); i++) {
    String email = emailList.get(i);
    if (email.equals(oldEmail)) {
        emailList.set(i, newEmail);
    }
}

Note that we used the equals method to check whether an email address string was the same as Jane’s previous email address. We will discuss the equals method later in this course.

Removing objects from a collection

Sometimes, you might need to remove some number of objects from a collection. The easiest and safest way to accomplish this task is to use a temporary collection object to store the objects you want to remove, and then use the removeAll method to remove them from the main collection.

For example, you might be concerned that email coming from the “evilhacker.com” site contains viruses. You could purge all addresses from this site from your email list as follows:

ArrayList<String> toRemove = new ArrayList<String>();

for (int i = 0; i < emailList.size(); i++) {
    String email = emailList.get(i);
    if (email.endsWith("@evilhacker.com")) {
        // mark this address for removal
        toRemove.add(email);
    }
}

emailList.removeAll(toRemove);

Summary

  • JUnit allows you to test a class by using assertions to check that calling methods on objects belonging to that class work correctly
  • Java arrays are really objects that are accessed by references, just like objects that are instances of a class
  • The length property of an array indicates how many elements an array object has
  • A multidimensional array in Java is really an array of references to arrays
  • Array elements are automatically initialized to a default value, which is 0 for numeric types and null for reference types (classes and arrays)

Licenses and Attributions


Speak Your Mind