Collection.toArray() method, detail about it

220 views Asked by At

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.

6

There are 6 answers

0
rocketboy On BEST ANSWER

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 a String[]

0
BobTheBuilder On

Array of objects is not array of Strings and can't be cast to one.

Check this.

1
Kayaman On

That version of toArray() returns Object[]. You can't cast an Object array into a String array even if all the objects in it are Strings.

You can use the lista.toArray(new String[lista.size()]); version to get the actual type correctly.

0
Taemyr On

use toArray(T[] a) instead.

Ie.

List<String> lista = new ArrayList<String>();
    lista.add("Lol");
    lista.add("ball");
    String [] array = lista.toArray(new string[1]);

This insures that toArray returns an array of type String[]

As others have noted, toArray() returns an array of type Object[], and the cast from Object[] to String[] is illegal.

0
sprite On

List lista = new ArrayList<>(); ---> List lista = new ArrayList();

0
Nerd Dragon On

There are two toArray() versions.You can use another one!