Java 将 ArrayList 转换为对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2745338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:22:24  来源:igfitidea点击:

Convert an ArrayList to an object array

javaarraysarraylist

提问by marionmaiden

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.

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

I want something like this:

我想要这样的东西:

ArrayList<TypeA> a;

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

TypeA[] array = MagicalCommand(a);

采纳答案by Mark Elliot

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

像标准Collection.toArray(T[])应该做你需要的东西(注意ArrayList实现Collection):

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

On a side note, you should consider defining ato 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为 typeList<TypeA>而不是ArrayList<TypeA>,这可以避免某些可能并不真正适用于您的应用程序的特定于实现的定义。

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

另外,请参阅该问题有关的使用a.size(),而不是0作为数组传递给大小a.toArray(TypeA[])

回答by Rachel

回答by jweber

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

回答by Shashank T

You can use this code

您可以使用此代码

ArrayList<TypeA> a = new ArrayList<TypeA>();
Object[] o = a.toArray();

Then if you want that to get that object back into TypeA just check it with instanceOf method.

然后,如果您希望将该对象返回到 TypeA,只需使用 instanceOf 方法检查它。

回答by user527619

Convert an ArrayList to an object array

将 ArrayList 转换为对象数组

ArrayList has a constructor that takes a Collection, so the common idiom is:

ArrayList 有一个接受 Collection 的构造函数,所以常见的习惯用法是:

List<T> list = new ArrayList<T>(Arrays.asList(array));

Which constructs a copy of the list created by the array.

它构造了由数组创建的列表的副本。

now, Arrays.asList(array)will wrap the array, so changes to the list will affect the array, and visa versa. Although you can't add or remove

现在,Arrays.asList(array)将包装数组,因此对列表的更改将影响数组,反之亦然。虽然你不能添加或删除

elements from such a list.

来自这样一个列表的元素。