问题描述
所以,通常 ArrayList.toArray()
会返回一种 Object[]
....但假设它是一个对象Custom
的Arraylist
,如何让toArray()
返回Custom[]
的类型而不是对象[]
?
So, normally ArrayList.toArray()
would return a type of Object[]
....but supposed it's an Arraylist
of object Custom
, how do I make toArray()
to return a type of Custom[]
rather than Object[]
?
推荐答案
像这样:
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
在 Java6 之前,建议这样写:
Before Java6 it was recommended to write:
String[] a = list.toArray(new String[list.size()]);
因为内部实现无论如何都会重新分配一个大小合适的数组,所以你最好提前做.由于 Java6 首选空数组,请参阅 .toArray(new MyClass[0]) 或 .toArray(new MyClass[myList.size()])?
because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
如果您的列表类型不正确,您需要在调用 toArray 之前进行强制转换.像这样:
If your list is not properly typed you need to do a cast before calling toArray. Like this:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
这篇关于使 arrayList.toArray() 返回更具体的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!