Java Reference
In-Depth Information
related code being scattered over several class definitions. This is a classical design dichotomy
discussed in the literature under the name of the “expression problem.” [ 4 ]
4 For a more complete explanation, see http://en.wikipedia.org/wiki/Expression_problem .
16.2.4. Richer forms of generics
This section discusses two limitations of Java generics and looks at a possible evolution to
mitigate them.
Reified generics
When generics were introduced in Java 5, they had to be backward-compatible with the existing
JVM. To this end, the runtime representations of ArrayList<String> and ArrayList<Integer> are
identical. This is called the erasure model of generic polymorphism. There are certain small
runtime costs associated with this choice, but the most significant effect for programmers is that
parameters to generic types can only be Objects. Suppose Java allowed, say, ArrayList<int>.
Then you could allocate an ArrayList object on the heap containing a primitive value such as int
42, but the Array-List container wouldn't contain any indicator of whether it contained an
Object value such as a String or a primitive int value such as 42.
As some level this seems harmless—if you get a primitive 42 from an ArrayList<int> and a
String object “abc” from an ArrayList<String>, then why should you worry that the ArrayList
containers are indistinguishable? Unfortunately, the answer is garbage collection, because the
absence of run-time type information about the contents of the ArrayList would leave the JVM
unable to determine whether element 13 of your ArrayList was an Integer reference (to be
followed and marked as “in use” by GC) or an int primitive value (most definitely not to be
followed).
In the C# language, the runtime representations of ArrayList<String>, ArrayList<Integer>, and
ArrayList<int> are all in principle different. But even if they are the same, sufficient type
information is kept at run-time to allow, for example, garbage collection to determine whether a
field is a reference or a primitive. This is called the reified model of generic polymorphism or,
more simply, reified generics . The word reification means “making explicit something that
otherwise would just be implicit.”
Reified generics are clearly desirable; they enable a more full unification of primitive types and
their corresponding object types—something that you'll see as problematic in the next sections.
 
Search WWH ::




Custom Search