小智..
49
我看到已经提供了一些解决方案,但没有任何原因,所以我将详细解释这一点,因为我认为知道你做错了什么同样重要,只是为了从给定的回复中得到"某些东西".
首先,让我们看看Oracle有什么话要说
*
The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
它可能看起来不重要,但正如你将看到的那样......那么以下行是什么失败了?列表中的所有对象都是String但它不会转换它们,为什么?
List tList = new ArrayList();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
也许你们中的许多人会认为这段代码也是如此,但事实并非如此.
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
实际上,编写的代码正在做这样的事情.javadoc说的是!它将实现一个新的数组,它将是什么对象!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
所以tList.toArray实例化一个对象而不是字符串......
因此,这个线程中没有提到的自然解决方案,但Oracle推荐的是以下内容
String tArray[] = tList.toArray(new String[0]);
希望它足够清楚.