سؤال

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.

هل كانت مفيدة؟

المحلول 2

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

نصائح أخرى

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.

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

Check this.

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.

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

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top