Why would not it work?
List<String> lista = new ArrayList<>();
lista.add("Lol");
lista.add("ball");
String [] array = (String[])lista.toArray();
It throws a RunTimeException (ClassCastException)
, I am aware that there is another method for the purpose of returning the object contained in the List, however what is happening behind the scenes? I mean I am casting an array of Objects which actually is an array of Strings to an Array of Strings. So it should compile, but it does not.
Thanks in advance.
List.toArray() returns an
Object[]
, because of type erasure. At runtime your list does not know if it has String objects. From there you can see where that error is coming from.You cannot type cast an
Object[]
into aString[]