Consider the following test of Java\'s ArrayList#toArray
method. Note that I borrowed the code from this helpful answer.
public class GenericTest {
The method Collection.toArray
cannot be changed for compatibility reasons.
However for your own code you can create a (more) type-safe helper method which protects you from the ArrayStoreException
if you use your method consequently:
public static T[] toArray(List extends T> list, T[] t) {
return list.toArray(t);
}
This method will reject String[] s=toArray(new ArrayList
which matches the example case of your question, but beware of the array subtyping rule: it will not reject
Object[] s=toArray(new ArrayList(), new String[0]);
because of the pre-Generics “String[]
is a subclass of Object[]
” rule. This can’t be solved with the existing Java language.