Why isn't the throw working?
I am trying to do this
List<String> stringList = new ArrayList<String>();
stringList.add("one");
stringList.add("two");
stringList.add("three");
(String[]) stringList.toArray();
why is this giving me a cast class exception?
Caused by: java.lang.ClassCastException: [Ljava.lang.Object;
Better try this other method:
String[] stringArray = stringList.toArray(new String[stringList.size()]);
This way the returned array is of the exact type you want, no casting is required. The method you are calling returns Object[]
, not String[]
, and the action you are trying to do is invalid.
The reason your code crashes is because it .toArray()
returns an array of type Object[]
that cannot be cast into String[]
. To fix this use another toArray(T[] a)
ie
stringList.toArray(new String[0]);
Since the toArray()
class method List
returns Object[]
not String[]
, and you cannot cast from Object[]
to String[]
. However, the correct way to do it is:
String[] array = new String[stringList.size()];
stringList.toArray(array);
or
String[] array = stringList.toArray(new String[stringList.size());
You cannot use a String array. Do you want to:
String [] test = stringList.toArray (new String [stringList.size ()]);
The method ArrayList<T>.toArray()
returns an array of type Object
, since this is a perfectly acceptable thing. In fact, due to the erasure of the styles, this is the only thing it can do.
If you want to get an array of type String
, call the method ArrayList<T>.toArray(T[])
. In your case, you would call it like this:
stringList.toArray(new String[3]);
A call of this type will contain the content ArrayList
in the presented array String
.