Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList fail to convert to a String array using (String[])list.toArray(). Why?

Why the below code fail to execute though it wont detect as an error from the IDE. And it will compile fine.

 ArrayList<String> a = new ArrayList<String>();
    a.add("one");
    a.add("two");
    a.add("three");
    String [] b = (String[])a.toArray();
    for(int i =0;i<b.length;++i){
        System.out.println(b[i]);
    }

But it will give the following error.

nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Can anyone give a clear explanation? The same problem has been asked before and some solutions has been provided. But a clear explanation of the problem will be much appreciated.

like image 446
prime Avatar asked Mar 24 '26 11:03

prime


2 Answers

You should simply do:

String[] b = new String[a.size()];
a.toArray(b);

You're getting the error because toArray() returns Object[] and this cannot be cast down to String[].

like image 67
Maroun Avatar answered Mar 26 '26 23:03

Maroun


You need to mention the type of array, else by default, toArray() would return an array of Object which can't be simply casted to String[]. If you specify the type, the overloaded toArray(T[]) would be called, returning the type of array mentioned as the parameter.

String [] b = a.toArray(new String[]{});
like image 30
Rahul Avatar answered Mar 27 '26 00:03

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!