Java Reference
In-Depth Information
If xArray were a reference to a real X[] object, it would be valid to store
both an X and a Z object into it. But xArray actually refers to a Y[] ob-
ject so it is not valid to store either an X reference or a Z reference in it.
Such assignments are checked at run time if needed to ensure that no
improper reference is stored into an array.
Like any other object, arrays are created and are subject to normal
garbage collection mechanisms. They inherit all the methods of Object
and additionally implement the Cloneable interface (see page 101 ) and
the Serializable interface (see " Object Serialization " on page 549 ) .
Since arrays define no methods of their own, but just inherit those of
Object , the equals method is always based on identity, not equivalence.
The utility methods of the java.util.Arrays classsee " The Arrays Utility
Class " on page 607 allow you to compare arrays for equivalence, and to
calculate a hash code based on the contents of the array.
The major limitation on the "object-ness" of arrays is that they cannot
be extended to add new methods. The following construct is not valid:
class ScaleVector extends double[] { // INVALID
// ...
}
In a sense, arrays behave like final classes.
Exercise 7.3 : Write a program that calculates Pascal's triangle to a
depth of 12, storing each row of the triangle in an array of the appro-
priate length and putting each of the row arrays into an array of 12 int
arrays. Design your solution so that the results are printed by a meth-
od that prints the array of arrays using the lengths of each array, not
a constant 12. Now change the code to use a constant other than 12
without modifying your printing method.
 
Search WWH ::




Custom Search