0

The Collection#toArray(T[]) signature is the following

public <T> T[] toArray(T[] a)

Most of the time, I write this code and everything works :

Collection<String> myCollection = Arrays.asList("foo", "bar");
String[] myArray = myCollection.toArray(new String[0]);

Today, I can't get my "usual" Collection<String> for some reasons, and then I came up with :

Collection myCollection = someNonGenericResult();
String[] myArray = myCollection.toArray(new String[0]);

And in this case, I get this compilation error :

incompatible types: java.lang.Object[] cannot be converted to java.lang.String[]

I know that I can cast the result of myCollection.toArray(new String[0]), but I would like to know why. I believed the method genericity could avoid that.

yunandtidus
  • 3,847
  • 3
  • 29
  • 42

0 Answers0