3

Java 7

I wrote this:

public static <E extends Enum<E>> List<SelectItem> getSelectItemList(Enum<E>... es){
    List<SelectItem> items = new ArrayList<SelectItem>();
    for(Enum<E> e : es){
        items.add(new SelectItem(e, e.toString()));
    }
    return items;
}

and this method compiled with no warning. Why? I expected that such using of varargs of a generic type (which is actually an array) produces

Potential heap pollution via varargs parameter es

Couldn't you explain it?

St.Antario
  • 26,175
  • 41
  • 130
  • 318

1 Answers1

2

Varargs of non - reifiable types tend to work like this. Enum<E> ... is effectively evaluated as Enum[] at runtime. At this point you can't be sure what references might get into the array.

More info here: https://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html

The Enum base type will actually give you some type - safety, even in compile time, so I guess this is why you are safe.

Danail Alexiev
  • 7,624
  • 3
  • 20
  • 28