Java Reference
In-Depth Information
It is possible that a variable of a parameterized type will refer to an object that is not of that
parameterized type. This situation is known as heap pollution .
Heap pollution can only occur if the program performed some operation involving a raw
type that would give rise to a compile-time unchecked warning (§ 4.8 , § 5.1.9 , § 5.5.2 ,
§ 8.4.1 , § 8.4.8.3 , § 8.4.8.4 , § 9.4.1.2 , § 15.12.4.2 ) , or if the program aliases an array variable
of non-reifiable element type through an array variable of a supertype which is either raw
or non-generic.
For example, the code:
Click here to view code image
List l = new ArrayList<Number>();
List<String> ls = l; // Unchecked warning
gives rise to a compile-time unchecked warning, because it is not possible to ascertain,
either at compile time (within the limits of the compile-time type checking rules) or
at run time, whether the variable l does indeed refer to a List<String> .
If the code above is executed, heap pollution arises, as the variable ls , declared to be a
List<String> , refers to a value that is not in fact a List<String> .
The problem cannot be identified at run time because type variables are not reified,
and thus instances do not carry any information at run time regarding the type argu-
ments used to create them.
In a simple example as given above, it may appear that it should be straightforward to
identify the situation at compile time and give an error. However, in the general (and
typical) case, the value of the variable l may be the result of an invocation of a separ-
ately compiled method, or its value may depend upon arbitrary control flow. The code
above is therefore very atypical, and indeed very bad style.
Furthermore, the fact that Object[] is a supertype of all array types means that unsafe
aliasing can occur which leads to heap pollution. For example, the following code
compiles because it is statically type-correct:
Click here to view code image
static void m(List<String>... stringLists) {
Object[] array = stringLists;
List<Integer> tmpList = Arrays.asList(42);
array[0] = tmpList; // (1)
String s = stringLists[0].get(0); // (2)
}
Search WWH ::




Custom Search