Heap Pollution
This valid Java code:
List numList = new ArrayList<Number>();
List<String> strList = numList;
The assignment to strList has resulted in what is known as a Heap Pollution. Java is a strongly typed language and the compiler is expected to raise an error but it will emit only an "unchecked warning". There are two issues that prevent the compiler from being strict here:
- Non-parameterized containers are allowed for compatibility with legacy code.
- The compiler cannot tell that the type of numList is not List<String> at the point of assignment to strList because this is possible: numList = new ArrayList<String>();
List<String> strList = numList;
If at the point of assignment, numList is still referring to an ArrayList<Number>, then the following code will result in a ClassCastException at runtime:
numList.add(1);
List<String> strList = numList;
List<String> strList = numList;
System.out.println (strList.get(0)); // ClassCastException
The solution is to follow the best programming practice of ensuring that all "unchecked warnings" are cleared before executing the code.