Article · Wikipedia archive · Last revised Jul 17, 2026

Heap pollution

In the Java programming language, heap pollution is a situation that arises when a variable of a parameterized type refers to an object that is not of that parameterized type. This situation is normally detected during compilation and indicated with an unchecked warning. Later, during runtime heap pollution will often cause a ClassCastException.

Last revised
Jul 17, 2026
Read time
≈ 1 min
Length
322 w
Citations
4
Source

In the Java programming language, heap pollution is a situation that arises when a variable of a parameterized type refers to an object that is not of that parameterized type.1 This situation is normally detected during compilation and indicated with an unchecked warning.1 Later, during runtime heap pollution will often cause a ClassCastException.2

Heap pollution in Java can occur when type arguments and variables are not reified at run-time. As a result, different parameterized types are implemented by the same class or interface at run time. All invocations of a given generic type declaration share a single run-time implementation. This results in the possibility of heap pollution.2

Under certain conditions, a variable of a parameterized type may refer to an object that is not of that parameterized type. The variable will always refer to an object that is an instance of a class that implements the parameterized type.

Heap Pollution in a non-varargs context

public class HeapPollutionDemo
{
    public static void main(String[] args)
    {
        Set s = new TreeSet<Integer>();
        Set<String> ss = s;              // unchecked warning
        s.add(new Integer(42));          // another unchecked warning
        Iterator<String> iter = ss.iterator();

        while (iter.hasNext())
        {
            String str = iter.next();    // ClassCastException thrown
            System.out.println(str);
        }
    }
}
Further reading

Further reading

References

References

  1. "The Java SE Tutorials". Oracle. Retrieved 16 July 2014.
  2. Langer, Angelika. "Java Generics FAQs: Heap pollution". angelikalanger.com/. Retrieved 15 July 2014.