Heap Pollution from Raw Types
What you'll learn: How using raw types can sneak incorrectly typed objects into generic collections, causing mysterious runtime failures.
The Danger Lurking Inside
When you use a raw type (a generic class without its type parameters), the compiler stops enforcing type safety. This creates heap pollution: a situation where a variable of a parameterized type points to an object that isn't actually of that type. The Java heap becomes "polluted" with objects whose runtime types don't match their compile-time declarations.
How It Happens
Imagine you declare a List<String> but assign it to a raw List reference somewhere in your code. Through that raw reference, you can now add anything—Integers, Doubles, custom objects—without compiler complaints. The JVM doesn't stop you because type parameters are erased at runtime.
Later, when code that expects a List<String> tries to retrieve elements, it assumes every object is a String. When it encounters that Integer you sneaked in? ClassCastException at runtime.
List<String> strings = new ArrayList<>();
List raw = strings; // Raw type reference to generic collection
raw.add(42); // Compiles with warning, but adds Integer!
String s = strings.get(0); // ClassCastException! Expected String, got Integer
The heap now contains an ArrayList that was supposed to hold only String objects but actually contains an Integer. That's heap pollution.
Why This Matters
Heap pollution violates the fundamental promise of generics: type safety. The error doesn't appear where you broke the rules (adding the Integer), but downstream where innocent code assumes the collection contract was honored. This makes debugging extremely difficult.
Key Takeaway: Raw types bypass generic type checking, allowing wrong-typed objects into collections and causing heap pollution that leads to unexpected ClassCastExceptions far from the source of the problem. Always use proper type arguments to maintain type safety.