【发布时间】:2021-03-28 01:52:17
【问题描述】:
所以,根据问题,我在 Java 中有这段代码:
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
}
}
问题是,虽然编译器对此没有任何反对意见,但在运行时我得到了这个错误:
线程“main”中的异常 java.lang.ArrayStoreException:arraycopy:元素类型不匹配:无法将 java.lang.Object[] 的元素之一转换为目标数组的类型 java.lang.String
我无法理解背后的原因 - 在我看来,我要求它用字符串填充一个字符串数组,那么为什么会出现错误?
【问题讨论】:
标签: java arrays arraylist toarray arraystoreexception