THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

A.3.2. API Issues


A second compatibility issue concerns the changes to the APIs themselves, within the class libraries. Many, if
not all, the generic types in the class libraries would have been written slightly differently had they been
written from scratch to be generic types. For example, a number of methods in the collections classes that
define a collection of T still take parameters of type Object. That was what the old signature specified, and
changing it would break compatibility.


As another example, the reflection method in java.lang.reflect.Array to create a new array is still
defined as


public static Object newInstance(Class<?> type, int length)


which has the unfortunate consequence that use of this method always results in an "unchecked" warning by
the compiler. A generic version might be specified as


public static T[] newInstance(Class type, int length)


but not only is that not backward compatible, it precludes creating arrays where the component type is a
primitive type. So even with a type-safe generic method, you'd still need a second method to allow primitive
array creation.


There is a similar problem with implementing the clone method: You cannot define a clone method for a
parameterized type without getting an "unchecked" warning when you cast the Object result of
Object.clone to the correct type. This is one of those rare occasions in which a cast using the expected
parameterized type is the right thing to do. For example, given a generic class Cell, the clone method
should be declared to return an instance of Cell because that will permit the caller of clone to use the
returned object without the need for any casts. To declare clone in that way requires that the result of
super.clone be cast to Cell, which incurs the "unchecked" warning. But be warned, an erroneous or
malicious clone implementation could still return an object of the wrong type.


As you generify you own applications and libraries you must be aware of these issues in order to maintain the
right level of compatibility with users of your code.


Things will get better despite our efforts to improve them.

Will Rogers

Appendix B. Useful Tables


How many seconds are there in a
year? If I tell you there are
3.155x10^7 you won't even try to
remember it. On the other hand,
who could forget that, to within
half a percent, π seconds is a
nanocentury?
Free download pdf