Chapter 9. Arrays

In this chapter, we introduce arrays and describe how to use them. Arrays in Java have pretty much the same features as arrays in many languages—the ability to store multiple variables all of one type, and access them by an index value.

Understanding and Creating Arrays

There are some neat features that flow from Java's rule that arrays are objects. That's a good place to start reviewing arrays.

Arrays are objects

When Java says arrays are objects, it means array types are reference types, and your array variable is really a reference to an array. What looks like the declaration of an array:

int day[];

is actually a variable that will point to an array-of-ints when you create that array. Notice that the array size is not mentioned in the declaration. When we finally fill in the pointer, it can point to any size of int array, and in the course of execution you can assign it different values to point to different arrays. You can't suddenly make an int array point to a char array, of course.

Here are some ways in which arrays are like objects:

  • They are objects because the language specification says so (“An object is a class instance or an array”, section 4.3.1).

  • Array types are reference types, just like object types.

  • Arrays are allocated with the “new” operator, similar to constructors.

  • Arrays are always allocated in the heap part of memory, never in the stack part of memory. Objects follow the same rule.

  • The parent class of all arrays is Object, and you can call any of the methods of Object, such as toString(), on an array.

On the other hand, here are some ways arrays are not like objects:

  • You can't extend an array type to create a new child array type.

  • Arrays have a different syntax from other object classes.

  • You can't define your own methods for arrays.

Regard arrays as funny kinds of objects that share some key characteristics with regular objects. Operations that are common to all objects can be done on arrays. Operations that require an Object as an operand can be passed an array.

When you write an array as the parameter to a method, you write it like this:

void main(String[] args) { ...

The array size is not part of the signature, so you can send across different-sized arrays as arguments in different calls. String[] matches any size array-of-Strings.

Index checking

Array indexes are all checked at run-time. If a subscript attempts to access an element outside the bounds of its array, it causes an exception and the program will cease execution rather than overwrite some other part of memory. Exceptions are described in Chapter 11.

The length of an array (the number of elements in it) is a data field in the array class. You can get the size of an array by referencing the following:

myArray.length      // yes

People always want to treat that as a method call, and write the following:

myArray.length()    // NO! NO! NO!

To remember this, remind yourself that arrays only have the method calls defined in java.lang.Object, and length() isn't one of them. So length must be a field for arrays. java.lang.String, on the other hand, is a regular class in all respects, is not an array of chars, and does have a length() method.

Creating an array

When you declare an array, as in the following example, that declaration says “carrot can hold a reference to any size array of int.”

int carrot [];

You have to make the reference point to an array before you can use it, just as with class types. You might make it point to an existing array, or you might create the array with a new expression, just as with objects.

carrot = new int[100];

An array is explicitly created by an array creation expression. Once an array has been created, it cannot change in size. You can make the reference variable point to a bigger array into which you copy the same contents.Class.

When you create an object, the fields that are primitive types are created and initialized to zero. The fields that are reference types are initialized to null (don't point to anything yet).

It is exactly the same with arrays. If the array element type is a primitive type, space for the values is allocated when the array is new'd[1]. The primitives are all set to zero, and you'll want to initialize them with whatever the appropriate value is before use.

carrot = new int [256];// creates 256 ints
carrot[7] = 32;       // ok, accesses 1 element.

If the array elements are a reference type, space for the references-to-objects is allocated, they are initialized to null, and you must fill them in before use!

Timestamp appts [] = new Timestamp[256]; // creates 256 null references
appts[7].hh = 10; // NO! NO! NO! (appts[7] is still null)

You need to make each individual reference element point to an object before you can access the object. You need to do something like this:

Timestamp appts [] = new Timestamp[256];
for (int i=0; i<appts.length; i++) {
     appts[i] = new Timestamp();
}

appts[7].hh = 10; // now OK!

Failing to create the objects in an array of reference types is the most common novice mistake with arrays, and it causes a NullPointerException error.

Array compatibility

Although you cannot declare an array type that extends another array type (the way you can with a class), there is a notion of type compatibility between arrays that have objects as their elements. If you have two arrays, one of a Parent class and one of a Child class, you can assign the array-containing-Child to the array-containing-Parent, and generally use it wherever an array-containing-Parent is expected.

Java has some standard classes like this:

class Number extends Object { /* more code */ }
class Integer extends Number { /*more code */ }

We can declare:

Number[] na;
Integer [] ia = new Integer[12];
void example(Numbers[] x) {/*more code */}

These statements are legal:

example(ia);  // sends an Integer[] which is compatible with Number[]
na = ia;       // assignment compatible

Initializing an array

You can initialize an array in its declaration with an array initializer like this:

byte b[] = { 0, 1, 1, 2, 3 };
String wkdays[] = { "Mon", "Tue", "Wed", "Thu", "Fri", };

A superfluous trailing comma is allowed in an initialization list—an unnecessary carryover from C. The permissible extra trailing comma is claimed to be of use when a list of initial values is being generated automatically.

A new array object is implicitly created when an array initializer expression is evaluated. You can't use an array initializer anywhere outside a declaration, like in an assignment statement. So this is not valid:

wkdays = { "Mon", "Tues" }; // NO! NO! NO!

But it is really useful to be able to allocate and initialize an array in a statement, so array creation expressions were brought to the rescue. It provides the explicit extra information about the type of the thing in braces. This is valid:

wkdays = new String[] { "Mon", "Tues", "Wed", "Thur", "Fri"};

That new type[] {value1, value2 } is an array creation expression, and it was introduced in JDK 1.1. You can use an array creation expression in a declaration or anywhere a reference to an array is expected. Here is one in a declaration.

Fruit orchard[] = new Fruit [] {new Fruit(),
                                new Fruit(4,3),
                                null };

Duplicating arrays

There is a method called arraycopy() in class java.lang.System that will copy part or all of an array, like this:

String midweek[] = new String[3];
System.arraycopy ( /*source*/       wkdays,
                   /*src offset*/   1,
                   /*dest*/         midweek,
                   /*dest offset*/  0,
                   /*len*/          3 );

You can clone an array, like this:

int p[] = new int[10];
int p2[] = (int[]) p.clone(); // makes a copy of p

Cloning creates a new array, whereas arraycopy just copies elements into an existing array. As with the clone of anything, you get back an Object which must be cast to the correct type. That's what ( int[] ) is doing.


[1] New'd is shorthand that some programmers use in place of instantiated.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.174.23