我看到有一些解决方案被提供了,但没有任何原因,所以我将详细解释一下,因为我认为知道你做错了什么比从给定的答复中获得"某些"能够工作更重要。
首先,让我们看看Oracle有什么要说的
* <p>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.
虽然看起来可能不重要,但正如您将看到的那样它确实很重要... 那么以下代码为什么会失败呢?列表中的所有对象都是字符串,但它没有将它们转换,为什么?
List<String> tList = new ArrayList<String>();
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实例化的是Objects而不是Strings...
因此,自然的解决方案并未在该线程中提到,但这正是Oracle推荐的做法:
String tArray[] = tList.toArray(new String[0])
希望这已经足够清楚了。