Java Reference
In-Depth Information
While perhaps confusing, this code compiles successfully. The cubics and temp
references are of the same type (a reference to an array of doubles ), so they can be assigned
to each other as on line 9. There is still only one array object in memory, so setting temp[5]
to
-1 is the equivalent of setting cubics[5] to
-1 . Figure 2.5 shows the state of the array
before line 12.
FIGURE 2.5
The array of cubic values has two references to it: cubics and temp .
0
1
2
3
1
8
27
64
125
-1
343
512
729
1000
cubics
temp
4
5
6
7
8
9
Here is the output of the ArrayDemo program:
-1.0
1.0 8.0 27.0 64.0 125.0 -1.0 343.0 512.0 729.0 1000.0
Setting cubics to null on line 12 still leaves temp pointing to the array. The array object
is not eligible for garbage collection until immediately after line 17 when temp is assigned
to a different array. By the way, the cubic values are lost at this point and temp refers to an
array with 20 new doubles , each of value 0.0 .
Multidimensional Arrays
Java allows for multidimensional arrays, up to as many dimensions as you require.
Declaring a reference to a multidimensional array consists of denoting a set of square
brackets for each dimension of the array. For example, the following values reference can
point to any two-dimensional array of chars , and names can refer to any three-dimensional
array of String references:
5. char [][] values;
6. String [][][] names;
Search WWH ::




Custom Search