Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Heap pollution occurs when a variable of a parameterized type references an object that is not of that parameterized type.  For more information on heap pollution, see the Java Language Specification, §4.12.2., "Variables of Reference Type," [JLS 2014]).

Mixing generically typed code with raw typed code is one common source of heap pollution. Generic types were unavailable prior to Java 5, so popular interfaces such as the Java Collection Framework relied on raw types.  Mixing generically typed code with raw typed code allowed developers to preserve compatibility between non-generic legacy code and newer generic code but also gave rise to heap pollution.  Heap pollution can occur if the program performed some operation involving a raw type that would give rise to a compile-time unchecked warning.

...

When generic and nongeneric types are used together correctly, these warnings can be ignored; at other times, these warnings can denote potentially unsafe operations. Mixing generic and raw types is allowed provided that heap pollution does not occur. For example, consider the following code snippet. In some cases, t is possible that a compile-time unchecked warning will not be generated. According to the Java Language Specification, §4.12.2.1, "Heap Pollution," [JLS 2005]:

Note that this does not imply that heap pollution only occurs if an unchecked warning actually occurred. It is possible to run a program where some of the binaries were compiled by a compiler for an older version of the Java programming language, or by a compiler that allows the unchecked warnings to suppressed [sic]. This practice is unhealthy at best.

...

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

OBJ03-J

low

probable

medium

P4

L3

Bibliography

[Bloch 2008]

Item 23. Don't use raw types in new code

[Bloch 2007]

[Bloch 2005]

Puzzle 88. Raw Deal

[Darwin 2004]

8.3, Avoid Casting by Using Generics

[JavaGenerics 2004]

 

[JLS 2005]

Chapter 5, Conversions and Promotions

 

§4.8, Raw Types

 

§5.1.9, Unchecked Conversion

[Langer 2008]

Topic 3, Coping with Legacy

[Naftalin 2006]

Chapter 8, Effective Generics

[Naftalin 2006b]

Principle of Indecent Exposure

[Schildt 2007]

Create a checked collection

[Tutorials 2008]

Heap Pollution

 

...

      Rule 05: Object Orientation (OBJ)Image Added