Does this cause heap pollution with varargs?

arrays, generics, java, variadic-functions

Solution

The warning about generic varargs is related to the dangers of generic arrays. Theoretically the method could abuse array covariance with the passed in array to cause heap pollution, for example:

Class<?>[] eventTypesWithWidenedType = eventTypes;
eventTypesWithWidenedType[0] = String.class;
Class<? extends Event> eventType = eventTypes[0]; // liar!

But it's fine as long as the method implementation doesn't do anything silly like that. Some basic precautions would be:

- Don't do any assignment to `eventTypes`.

- Don't return or otherwise expose `eventTypes` outside the method.

With Java 7, you could annotate the method with @SafeVarargs, which basically promises the compiler that generic arrays are okay (meaning it's no longer on the caller to suppress the warning).

Problem

I am getting the warning: [unchecked] Possible heap pollution from parameterized vararg type Class But I am unsure if it will actually pollute: ``` public void register(EventListener listener, Class<? extends Event>... eventTypes) {} ``` Here is the complete implementation if that is necessary: ``` public class EventDispatcher { public static ConcurrentLinkedQueue<Event> eventQueue; public static ConcurrentHashMap<Class<? extends Event>, CopyOnWriteArrayList<EventListener>> eventsListenerMap = new ConcurrentHashMap<>(); public static void register(EventListener listener, Class<? extends Event>... eventTypes) { for (Class<? extends Event> eventType : eventTypes) { if (eventsListenerMap.containsKey(eventType)) { eventsListenerMap.get(eventType).addIfAbsent(listener); } else { CopyOnWriteArrayList<EventListener> initializingListeners = new CopyOnWriteArrayList<>(); initializingListeners.add(listener); eventsListenerMap.put(eventType, initializingListeners); } } } } ``` I am all up for OT-suggestions for improving this, too, but keep in mind that this class is unfinished.

Original source