Heap Pollution from Raw Types
What you'll learn: How mixing raw types with generics can sneak corrupted data into your collections, causing mysterious ClassCastException errors where you never wrote a cast.
What Is Heap Pollution?
Heap pollution occurs when a variable of a parameterized type (like List<String>) actually points to an object that contains data of a different type. This happens when you bypass generics' compile-time safety checks—most commonly by using raw types.
Think of it like labeling a jar "SUGAR" but then pouring salt into it through an unlabeled funnel. Later, when someone trusts the label and uses the contents, they get a nasty surprise.
How Raw Types Cause Heap Pollution
When you mix raw types with generic types, the compiler can't verify type safety:
List<String> strings = new ArrayList<>();
List rawList = strings; // Raw type reference to generic object
rawList.add(42); // Compiles! No type checking on raw list
// Later, when you use the "safe" strings reference:
String s = strings.get(1); // ClassCastException! No explicit cast in YOUR code
You never wrote (String), yet Java tried to cast Integer to String behind the scenes. This is heap pollution—the List<String> object now contains an Integer, violating its type contract.
Why This Is Dangerous
The exception happens far from where you broke the rules. The rawList.add(42) line looks innocent. The crash occurs at strings.get(1), confusing anyone debugging without seeing the raw type usage.
Type erasure makes this possible: at runtime, both List<String> and raw List are just List, allowing incompatible references to point to the same object.
Key Takeaway: Heap pollution occurs when raw types allow wrong-typed data into generic collections, causing ClassCastException in code that looks type-safe. Always avoid raw types to prevent corrupting your data structures.