使 arrayList.toArray() 返回更具体的类型
因此,通常 ArrayList.toArray()
会返回 Object[]
类型......但假设它是一个 对象 Custom
的 Arraylist
,如何使 toArray()
返回 Custom[]
类型而不是对象[]
?
So, normally ArrayList.toArray()
would return a type of Object[]
....but supposed it's anArraylist
of object Custom
, how do I make toArray()
to return a type of Custom[]
rather than Object[]
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
像这样:
在 Java6 之前,建议这样写:
因为内部实现无论如何都会重新分配一个适当大小的数组,所以你最好提前完成它。由于 Java6 首选空数组,请参阅 .toArray(new MyClass[0]) 或 .toArray(new MyClass[myList.size()]) ?
如果您的列表类型不正确,您需要在调用 toArray 之前进行强制转换。像这样:
Like this:
Before Java6 it was recommended to write:
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()])?
If your list is not properly typed you need to do a cast before calling toArray. Like this:
将 List 转换为特定类型(例如 Long)的 Array 的较短版本:(
可从 java 11 获得)
A shorter version of converting List to Array of specific type (for example Long):
(available from java 11)
它实际上并不需要返回
Object[]
,例如:-这是我的
Custom
类:-It doesn't really need to return
Object[]
, for example:-Here's my
Custom
class:-http://download.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object[]%29
http://download.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object[]%29
我得到了答案...这似乎工作得很好
I got the answer...this seems to be working perfectly fine
以下解决方案适用于我的情况。
The following solution is for my case.