printItems("Hi there", "World");
printItems(1, 2, 3, 4, 5);
printItems(1.1, 2.2, 3.3);
Be careful for heap air pollution
One of many foremost issues when utilizing varargs with generics is heap air pollution. Heap air pollution happens when the parameterized kind of a variable doesn’t agree with the kind of the objects it factors to. This will occur as a result of varargs arguments are applied as an array, and arrays in Java don’t have the identical type-specificity as generics. For example, contemplate this methodology:
public static <T> void harmful(Checklist<T>... lists) {
Object[] objects = lists; // Implicit casting to Object array
objects[0] = Arrays.asList(1); // Assigning a Checklist<Integer> to a Checklist<T> array
T first = lists[0].get(0); // ClassCastException thrown right here if T shouldn't be Integer
}
On this instance, you possibly can go Checklist<String>[]
to the strategy, however inside the strategy, it’s attainable to insert a Checklist<Integer>
, resulting in a ClassCastException
whenever you attempt to retrieve an Integer
as if it have been a String
.
Addressing heap air pollution with @SafeVarargs
Java 7 launched the @SafeVarargs
annotation to handle the heap air pollution difficulty. This annotation asserts that the strategy doesn’t carry out probably unsafe operations on its varargs parameter. It must be used solely when the strategy is actually secure from heap air pollution—that’s, it doesn’t retailer something within the generic varargs array or do something to make it accessible to untrusted code.