7

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?

Community
  • 1
  • 1
Albert
  • 65,406
  • 61
  • 242
  • 386

3 Answers3

15

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.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • 3
    The mentioned Project Coin feature is now available - see [@SafeVarargs](http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html) in Java 7. – George Hawkins Jul 17 '12 at 14:46
5

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

Community
  • 1
  • 1
Bert F
  • 85,407
  • 12
  • 106
  • 123
0

You can try this:

<T> void foo(T... a) { /*...*/ }
Eugene Kuleshov
  • 31,461
  • 5
  • 66
  • 67