Let's take this sample Java method:
public static <E> HashSet<E> createHashSet(final E... elements) {
final HashSet<E> hashSet = new HashSet<E>(elements.length);
java.util.Collections.addAll(hashSet, elements);
return hashSet;
}
If I'm compiling with Java 17 using -Xlint:all
, I get the following warning for the method signature:
Varargs method could cause heap pollution from non-reifiable varargs parameter iterators
Eclipse 2022-09 suggests using @SafeVarargs
. And indeed Java's own java.util.Collections.addAll(…)
itself uses @SafeVarargs
! Yet when I add it to the method signature, javac
gives me the same warning, only further down in the java.util.Collections.addAll(…)
line.
The answers to java warning: Varargs method could cause heap pollution from non-reifiable varargs parameter suggest additionally using @SuppressWarnings("varargs")
on the method for IntelliJ. And indeed when I use both @SafeVarargs
and @SuppressWarnings("varargs")
together, the lint warning goes away with javac
. However Eclipse says this annotation value "varargs"
is unsupported.
Eclipse also suggests using @SuppressWarnings("unchecked")
. If I add only @SuppressWarnings("unchecked")
to the method, then the warning goes away both in Eclipse and in javac
with linting! So it would seem that a single @SuppressWarnings("unchecked")
is the way to go.
But is it? https://stackoverflow.com/a/47949197 seems to indicate that the way to go for IntelliJ is @SafeVarargs
and @SuppressWarnings("varargs")
together, and https://stackoverflow.com/a/44675766 seems to agree in general. And the source code for Java uses @SafeVarargs
.
Is Eclipse incorrect in forcing me to use @SuppressWarnings("unchecked")
instead of @SafeVarargs
and @SuppressWarnings("varargs")
together? I have opened Eclipse Issue #453 to try to get more answers.
Note on duplicates
Note that java warning: Varargs method could cause heap pollution from non-reifiable varargs parameter does not seem to be a duplicate; it is about avoiding this warning on IntelliJ. The solution there does not work for Eclipse.