Possible heap pollution... but what does it mean really?

I have this method:

    @SafeVarargs
    public final <T extends AABB> List<T> insideAABB(AABB container, boolean trimToCircle, List<T>... candidates) {
        ...
    }

Its tagged with @SafeVarargs to get rid of the compiler warning, but I’m not sure when I would would not be safe. And just how bad is a polluted heap anyway? From what I can see it only means ClassCastExceptions, which don’t have much of a lifespan in an average debugging cycle…

Have a look at: https://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html

It has to do with how Java implements parameterized types. Java uses type-erasure as opposed to how C# goes about implementing parameterized types using templating by making many specializations/realizations of the same class for each actual type argument used.

Simply put, a vararg (or any array) of a parameterized type, such as List, is a non-reifiable type, meaning that neither the compiler nor the runtime can make sure that whatever is in an array element, is in fact a List of T’s and not a List of Strings for example. It only knows that it is a List, but not what that List contains.

And that’s because, even though arrays themselves can be generic, this does not go down another layer if the array’s component type itself is a parameterized type. There the compiler loses the type information.
And because at runtime, all List are simply compiled to the unparameterized raw type “List,” even the runtime cannot and will not make sure that your List in fact contains 'T’s and nothing else.

So to summarize: Because of the way Java implements parameterized types, we cannot get rid of this warning, but have to use either @SuppressWarnings(“unchecked”) at times or this @SafeVarargs. Using List<T>... in your code you just express the “intent” to a client of that method what it should invoke that method with. But that is not enforced.

Thanks for the explanation - I always understood “unchecked”, but “potential heap pollution” sounds a bit Chernobyl. I always had a vague suspicion I was doing something desperately wrong. Thanks for clearing it up.