Heap pollution

Source: Wikipedia, the free encyclopedia.

In the

runtime heap pollution will often cause a ClassCastException.[2]

Heap pollution in Java can occur when type arguments and variables are not

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

  • Gosling, James; Joy, Bill; Steele, Guy; Bracha, Gilad; Buckley, Alex (2014). "4.12.2". The Java Language Specification, Java SE 8 Edition. Addison-Wesley. pp. 81โ€“82. .
  • Friesen, Jeff (2011). Beginning Java 7. Expert's voice in Java. Apress. p. 211. .
  • Reese, Richard; Reese, Jennifer (2012). Java 7 New Features Cookbook (PDF). Packt Publishing. pp. 38โ€“40. .
  • Stenzel, Kurt; Grandy, Holger; Reif, Wolfgang (2008). "Verification of Java Programs with Generics". Algebraic Methodology and Software Technology. Lecture Notes in Computer Science. Vol. 5140. pp. 315โ€“329. .(subscription required)

References

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