Java Arrays



next up previous
Next: The Java Type Up: Interaction of Parameterization Previous: Primitive Types

Java Arrays

 

While the current Java language does not support parameterization of classes or interfaces, there is support for parameterized arrays. Unfortunately, the subtyping rule for Java arrays is different from the subtyping rule we propose in Section 3 for parameterized classes and interfaces.

The subtyping rule for Java arrays does allow subtypes that are covariant in the parameter types. If S is a subtype of T, an array of S (written S[]) is a subtype of an array of T (T[]). This rule has the consequence that array stores require a runtime type check, and this check is in fact made by the Java runtime. For example, consider the following code:


        T x = ...;
  *     T[] z = new S[] (...);
        ...;
  **    z[i] = x;

The assignment (*) is legal because S is a subtype of T and therefore S[] is a subtype of T[]. The assignment (**) is also legal (at compile time) because it is legal to store a T object into a T[]. However, if this store were allowed to happen, the result would be that an S[] contains an element whose type is not a subtype of S. Therefore the store cannot be permitted, and Java prevents it by checking at runtime that the actual type of the object being stored is a subtype of the element type of the array*.

The motivation for the Java subtyping rule seems to be that it is better to check stores at runtime than to copy the entire array when a conversion from S[] to T[] is desired. While this may be true for some programs, it is not difficult to imagine programs in which stores are a dominant cost; for general parameterized types, it is even easier to imagine costly situations, since every method that takes an argument of a parameter type would require the check.

We believe that for general parameterization of classes and interfaces it is better not to allow covariant-parameter subtyping. It would be possible to allow such subtyping if no methods of the supertype take arguments of the parameter type, but such types are rare. (A more complete discussion of these issues is available [DGLM95].) Furthermore, covariant-parameter subtyping creates implementation difficulties for efficient dispatch mechanisms [Mye95][Str87]. We believe that the Java rule for arrays should be changed so that all parameterized types have the same rule. However, our design does not require this; different rules can be used for arrays and for other parameterized types.



next up previous
Next: The Java Type Up: Interaction of Parameterization Previous: Primitive Types

Andrew C. Myers, Joseph A. Bank, Barbara Liskov
Copyright © 1996 Association for Computing Machinery