|
|
Java(TM) provides several classes for managing sets or collections of data, for example, Vector (see java.util.Vector). And, of course, you can design your own classes. In addition, there is support for arrays. A Java array is different from a user-defined container object such as a Vector instance in the sense that the Java type system provides built-in, language-level syntactic support for arrays, as do many other languages. Although language-level support for arrays increases the complexity of the language definition, it's justified (in the minds of most programmers) because array usage is entrenched in traditional programming. An array is a linear collection of data elements, each element directly accessible via its index. The first element has index 0; the last element has index n - 1. The array has the form:
The syntax for creating an array object is:
This declaration defines the array object--it does not allocate memory for the array object, nor does it allocate the elements of the array. Also, you may not specify a size within the square brackets. To allocate an array, use the new operator:
int[] x = new int[5]; // array of five elements
The array x of Java primitives has the form:
Consider an array definition for a user-defined type such as Dog:
Dog[] dog = new Dog[5];
This definition creates the array object itself, but not the elements:
Subsequently, you can use the new operator to create objects in order to initialize the array elements (which are reference variables):
dog[0] = new Dog();
...
dog[4] = new Dog();
To create multidimensional arrays, simply create arrays of arrays, for example,
T[][] t = new T[10][5];
This definition creates ten arrays of references to arrays of references for objects of type T. This definition does not allocate memory for instances of T. There is a short-hand notation for defining an array and initializing its elements in one step using comma-separated data values between curly brackets:
The following table provides examples:
Note that the array size is determined from the number of initializers. Accessing an undefined array element causes a runtime exception called ArrayIndexOutOfBoundsException. Accessing a defined array element that has not yet been assigned to an object results in a runtime exception called NullPointerException. Arrays are useful for enhancing the versatility of our user-defined type Dog. Suppose we add an array variable to store a dog's daily diet:
class Dog {
String[] dailyDiet = null;
String barkSound = "Woof.";
String name = "none";
String breed = "unknown";
...
dailyDiet is initialized to null, suggesting that there is no legitimate default value. That is, the class definition assumes that an access method will initialize this field, and methods that use this variable should handle a null value gracefully. Next, we provide access methods for setting and getting the diet:
void setDiet(String[] diet) {
dailyDiet = new String[diet.length];
for (int i = 0; i < diet.length; i++)
dailyDiet[i] =diet[i];
}
String[] getDiet() {
return dailyDiet;
}
setDiet() creates an (instance variable) array dailyDiet from the array passed as an argument, represented by the parameter diet. setDiet() uses the length variable of the parameter diet (available for all arrays) to determine the number of elements. This value appears directly within the "[]" brackets following the new operator to allocate the required number of elements, each of which can hold a String reference variable. In this situation, we use the for construct to iterate over the array. The for construct has the syntax:
for (<init-stmts>...; <boolean-expression>; <exprs>...) The iteration control area for the for statement has three semicolon-separated components. The first component <init-stmts>... is one or more comma-separated initializations, performed once prior to the first iteration. The third component <exprs>... is one or more comma-separated expressions, performed after each iteration cycle. The second component is the iteration test condition. As with a while statement, this test is performed before each iteration cycle. The for loop control area initializes one index variable i to 0. After each iteration its value is incremented so that it indexes the next element in the array. In the statement group area (the loop body), we copy each reference variable array element from the parameter array to the instance variable array. The following method demonstrates that the Dog class definition must handle null values for dailyDiet gracefully:
void displayDiet() {
if (dailyDiet == null) {
System.out.println(
"No diet established for " + getName() + ".");
return;
}
else {
System.out.println(
"The diet established for " + getName() + " is:");
for (int i = 0; i < dailyDiet.length; i++)
System.out.println(dailyDiet[i]);
}
}
The following program creates a Dog instance, establishes its daily diet, and displays the diet:
public class DogDiet {
public static void main(String[] args) {
Dog fido = new Dog();
fido.setName("Fido");
String[] diet = {
"2 quarts dry food",
"1 can meat",
"2 buckets fresh water"
};
fido.setDiet(diet);
fido.displayDiet();
}
}
DogDiet produces the following output:
D:\>java DogDiet
The diet established for Fido is:
2 quarts dry food
1 can meat
2 buckets fresh water
Exercisecopyright 1996-2000 Magelang Institute dba jGuru |
|