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.[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

* 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. ISBN 978-0-13-390069-9. https://books.google.com/books?id=mh-KAwAAQBAJ&pg=PA81.
* Friesen, Jeff (2011). Beginning Java 7. Expert's voice in Java. Apress. p. 211. ISBN 978-1430239093. https://books.google.com/books?id=CwSaQpCtfPkC&pg=PA211.
* Reese, Richard; Reese, Jennifer (2012). Java 7 New Features Cookbook. Packt Publishing. pp. 38-40. ISBN 978-1-84968-562-7. http://dl.e-book-free.com/2013/07/java_7_new_features_cookbook.pdf.

## References

1. ↑ 1.0 1.1 "The Java SE Tutorials". Oracle. http://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html#heap_pollution. Retrieved 16 July 2014.
2. ↑ 2.0 2.1 Langer, Angelika. "Java Generics FAQs: Heap pollution". http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Topic2. Retrieved 15 July 2014.

0.00

(0 votes)

Original source: https://en.wikipedia.org/wiki/Heap pollution. Read more

|

Retrieved from "https://handwiki.org/wiki/index.php?title=Heap_pollution&oldid=3009049"