Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Type safety : A generic array of A is created for a varargs parameter [duplicate]

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?

like image 692
Albert Avatar asked Oct 20 '10 19:10

Albert


Video Answer


2 Answers

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.

like image 166
ColinD Avatar answered Sep 21 '22 03:09

ColinD


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

like image 42
Bert F Avatar answered Sep 18 '22 03:09

Bert F