casting – Java: Type safety : A generic array of A is created for a varargs parameter – Education Career Blog

Possible Duplicate:
Is it possible to solve the “A generic array of T is created for a varargs parameter” compiler warning?

Consider this is given:

interface A<T> { /*...*/ }
interface B<T> extends A<T> { /*...*/ }
class C { /*...*/ }
void foo(A<T>... a) { /*...*/ }

Now, some other code wants to use foo:

B<C> b1 /* = ... */;
B<C> b2 /* = ... */;
foo(b1, b2);

This gives me the warning

Type safety : A generic array of A is created for a varargs parameter

So I changed the call to this:

foo((A<C>) b1, (A<C>) b2);

This still gives me the same warning.

Why? How can I fix that?

,

All you can really do is suppress that warning with @SuppressWarnings("unchecked"). Java 7 will eliminate that warning for client code, moving it to the declaration of foo(A... a) rather than the call site. See the Project Coin proposal here.

,

Edit: Answer updated to reflect that question was updated to show A is indeed generic.

I would think that A must be a generic to get that error. Is A a generic in your project, but the code sample above leaves the generic decl out?

If so, Because A is generic, you can’t work around warning cleanly. Varargs are implemented using an array and an array doesn’t support generic arrays as explained here:

Java generics and varargs

,

You can try this:

<T> void foo(T... a) { /*...*/ }

Leave a Comment