Java Reference
In-Depth Information
mergedLists.addAll(lists[i]);
return mergedLists;
}
}
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 SafeVarargsDemo.java
:
SafeVarargsDemo.java:15: warning: [unchecked] unchecked
generic array creation for
varargs parameter of type
List<String>[]
System.out.println(merge(list1, list2)); // Output:
[A, B, C, D, E]
^
SafeVarargsDemo.java:18: 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.
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.