public class example {
static ArrayList<String[]> test = new ArrayList<String[]>();
private String[] a = {"this", "is,", "a test"};
private String[] b = {"Look", "a three-headed", "monkey"};
public void fillTest() {
test.add(a);
test.add(b);
// so far so good, I checked this method
// with a System.out.print and it works
}
// later in the code I have a method that try
// to take the arrayList test and copy it into
// a String[] named temp. In my vision temp
// should than be accessed randomly by the
// method itself and the content printed out
// from temp should be removed from test -
// that's why I'm using an ArrayList
public void stuff() {
// some stuff
// runtime error happens here:
String[] temp = test.toArray(new String[test.size()]);
// other stuff that never made it to runtime
}
}
The problem is that while the compiler has nothing against this, at Runtime I get this error:
Exception in thread "main" java.lang.ArrayStoreException: arraycopy: element type mismatch: can not cast one of the elements of java.lang.Object[] to the type of the destination array, java.lang.String
I can't understand the reason behind - looks to me like I'm asking it to fill an Array of Strings with strings, so why the error?
You are trying to convert a List
whose elements are arrays of String
to an array whose elements are String
s. This doesn't work, since an array of String
is not a String
.
Instead, you can convert your List
of arrays to a 2D array of String
s:
String[][] temp = test.toArray(new String[test.size()][]);
If you want to put all the elements of the String arrays of the List
in a single array of String
, you have to do some processing. With Stream
s it can be done with:
String[] temp = test.stream().flatMap(Arrays::stream).toArray(String[]::new);