Search code examples
javastringarraylisttoarray

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.


Solution

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