将 ArrayList 转换为对象数组 [英] Convert an ArrayList to an object array

查看:50
本文介绍了将 ArrayList 转换为对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java 中是否有将 ArrayList 转换为对象数组的命令.我知道如何将每个对象从 arrayList 复制到对象数组中,但我想知道它是否会自动完成.

Is there a command in java for conversion of an ArrayList into a object array. I know how to do this copying each object from the arrayList into the object array, but I was wondering if would it be done automatically.

我想要这样的东西:

ArrayList<TypeA> a;

// Let's imagine "a" was filled with TypeA objects

TypeA[] array = MagicalCommand(a);

推荐答案

类似于标准的Collection.toArray(T[]) 应该做你需要的(注意 ArrayList 实现 <代码>集合):

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

附带说明,您应该考虑将 a 定义为 List 而不是 ArrayList,这避免某些可能并不真正适用于您的应用程序的特定于实现的定义.

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

另外,请参阅这个问题关于使用a.size() 而不是 0 作为传递给 a.toArray(TypeA[])

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

这篇关于将 ArrayList 转换为对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆