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;
source to share
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.
source to share
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());
source to share
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
.
source to share