在Java中将列表转换为数组 [英] Convert list to array in Java

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

问题描述

如何在 Java 中将 List 转换为 Array?

How can I convert a List to an Array in Java?

检查下面的代码:

ArrayList<Tienda> tiendas;
List<Tienda> tiendasList; 
tiendas = new ArrayList<Tienda>();

Resources res = this.getBaseContext().getResources();
XMLParser saxparser =  new XMLParser(marca,res);

tiendasList = saxparser.parse(marca,res);
tiendas = tiendasList.toArray();

this.adaptador = new adaptadorMarca(this, R.layout.filamarca, tiendas);
setListAdapter(this.adaptador);  

我需要用 tiendasList 的值填充数组 tiendas.

I need to populate the array tiendas with the values of tiendasList.

推荐答案

要么:

Foo[] array = list.toArray(new Foo[0]);

或:

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

<小时>

请注意,这仅适用于引用类型的数组.对于原始类型的数组,使用传统方式:


Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

<小时>

更新:

现在推荐使用list.toArray(new Foo[0]);,而不是list.toArray(new Foo[list.size()]);.

来自 JetBrains Intellij Idea 检查:

有两种样式可以将集合转换为数组:使用预先确定大小的数组(如 c.toArray(new String[c.size()]))或使用空数组(如 c.toArray(new String[0]).

In建议使用预先调整大小的数组的旧 Java 版本,因为创建适当大小的数组所必需的反射调用很慢.但是,由于 OpenJDK 6 的更新较晚,此调用被内化,使得空数组版本的性能与预装尺寸相同,有时甚至更好版本.此外,传递预定大小的数组对于并发或同步收集作为数据竞争是可能的sizetoArray 调用可能会导致额外的空值在数组的末尾,如果集合同时收缩在操作过程中.

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

此检查允许遵循统一风格:要么使用空数组(建议在现代 Java)或使用预先确定大小的数组(在较旧的 Java 版本或非基于 HotSpot 的 JVM).

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

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

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