Reputation: 1411
I am using a ArrayList to store some Strings form an array of strings:
ArrayList<String> list = new ArrayList<>();
list.add(strings[i]);
To give those to another function I converted them back into an Array:
foo((String[]) list.toArray());
this gives me an exeption:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
What am I doing wrong here?
Upvotes: 2
Views: 218
Reputation: 6145
You have to do
String[] t = new String[list.size()];
foo(list.toArray(t));
Upvotes: 1
Reputation: 86409
The method call list.toArray()
returns an array of type Object[]. You can't cast that to String[], even though it contains only Strings.
But you can create an array of type String[] with a sibling of List.toArray() that accepts an initial array of the desired type:
foo( list.toArray( new String[ list.size() ] ) );
Upvotes: 5