List.toArray()
is a method in the interface List
, and the documentation does not specify what kind of array is returned by the method. However, unlike other answers suggested, the List.toArray()
method cannot return an array of the generic type of the list, because the generic type of a list is not known at runtime.
Because of that, all the implementations of List
that are built-in to the standard API return an Object[]
, and not a String[]
.
However, you are allowed to pass your own pre-allocated array into the method List.toArray(Object[])
. If you do that, you are guaranteed to get a return value that has the same element type as the array that you passed in. If the array that you passed in has the same size as the list itself, then that array will be used (otherwise, a new array of the proper size is allocated internally)
This will fix it:
public void method1(List s) {
String[] array = s.toArray(new String[s.size()]); // <-- pass the array as an argument
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}