Java Reference
In-Depth Information
This is codified in the Producer Extends, Consumer Super
(PECS) principle coined by Joshua Bloch.
As we will see in Chapter 8 , we see both covariance and contravariance throughout
the Java Collections. They largely exist to ensure that the generics just “do the right
thing” and behave in a manner that should not surprise the developer.
Array Covariance
In the earliest versions of Java, before the collections libraries were even introduced,
the problem of type variance in container types was still present for Java's arrays.
Without type variance, even simple methods like this sort() would have been very
difficult to write in a useful way:
Arrays . sort ( Object [] a );
For this reason, arrays in Java are covariant—this was seen as a necessary evil in the
very early days of the platform, despite the hole in the static type system that it
// This is completely legal
String [] words = { "Hello World!" };
Object [] objects = words ;
// Oh, dear, runtime error
objects [ 0 ] = new Integer ( 42 );
More recent research on modern open source codebases indicates that array cova‐
riance is extremely rarely used and is almost certainly a language misfeature. 2 It
should be avoided when writing new code.
Generic Methods
A generic method is a method that is able to take instances of any reference type.
For example, this method emulates the behavior of the , (comma) operator from
the C language, which is usually used to combine expressions with side effects
// Note that this class is not generic
public class Utils
public static < T > T comma ( T a , T b ) {
return a ;
2 Raoul-Gabriel Urma and Janina Voigt, “Using the OpenJDK to Investigate Covariance in Java,”
Java Magazine (May/June 2012):44-47.
Search WWH ::

Custom Search