Java Reference
In-Depth Information
return mergedLists;
Listing3-58 declaresa merge() methodwhosepurposeistomergeavariableum-
ber of List of String arguments into a single List of String that this method
returns. Because erasure converts the method's List<String> parameter type to
List , there is a potential for this array parameter to refer to a List that doesn't
store String objects, which is an example of heap pollution. For this reason, the
compiler emits the following warnings when you compile Listing 3-58 via javac -
Xlint:unchecked : warning: [unchecked] unchecked
generic array creation for varargs parameter of type
System.out.println(merge(list1, list2)); // Output:
[A, B, C, D, E]
^ warning: [unchecked] Possible heap
pollution from parameterized vararg type List<String>
static List<String> merge(List<String>... lists)
2 warnings
The merge() method does nothing that can lead to a ClassCastException .
Therefore, these warning messages are spurious and can be ignored by annotating
merge() with @SafeVarargs toassertthatthebodyofthe merge() methoddoes
not perform potentially unsafe operations on its varargs parameter.
Uncomment //@SafeVarargs in Listing3-58 andrecompile.You'lldiscoverthat
these warning messages disappear.
Note Variousstandardclasslibrarymethods,suchasthe Arrays class's public
static <T> List<T> asList(T... a) method, are annotated
@SafeVarargs because they don't throw ClassCastException s when their
varargs array arguments are created by the compiler using proper type inference.
Search WWH ::

Custom Search