How to handle type erase in Advanced Java Generics


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

Beware of pollution of a pile

One of the manual concerns in using varargs with generics is the pollution of the heap. The pollution of the heap occurs when the parameterized type of variable fees disagrees with the type of objects it points to. This may happen because varargs arguments are implemented as fields and fields in Java Don have the same specificity as a generation. For example, consider this method:


public static <T> void dangerous(List<T>... lists) {
    Object() objects = lists; // Implicit casting to Object array
    objects(0) = Arrays.asList(1); // Assigning a List<Integer> to a List<T> array
    T first = lists(0).get(0); // ClassCastException thrown here if T is not Integer
}

In this example you can pass on List<String>() To the method but inside the method can be inserted and List<Integer>which leads ka ClassCastException When you try to load Integer as if yes String.

Addressing the pile of pile with @Safevargs

Java 7 introduced @SafeVarargs Annotation to solve pollution of a pile. This annotation claims that the method does not perform potentially dangerous operations on its Varargs parameter. It should only be used when the method is truly safe from the pollution of the heap – that is, it does not store anything in the general Varargs field or does anything to be accessible to the untrustworthy code.

Leave a Comment