Methods to deal with kind erasure in superior Java generics

Learn extra at:


printItems("Hiya", "World");
printItems(1, 2, 3, 4, 5);
printItems(1.1, 2.2, 3.3);

Be careful for heap air pollution

One of many predominant considerations 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. As an illustration, take into account 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 move Checklist<String>[] to the strategy, however inside the strategy, it’s potential 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 concern. This annotation asserts that the strategy doesn’t carry out doubtlessly unsafe operations on its varargs parameter. It must be used solely when the strategy is really protected 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.

Turn leads into sales with free email marketing tools (en)

Leave a reply

Please enter your comment!
Please enter your name here