java - 在Java中将列表转换为数组

标签 java arrays list arraylist

如何在 Java 中将 List 转换为 Array

检查下面的代码:

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

最佳答案

要么:

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

或:

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

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

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 检查:

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.

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 - 在Java中将列表转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572795/

相关文章:

java - 如何在不损失纳秒级精度的情况下使用 TimeUnit.timedWait()?

java - 删除android应用程序的标题栏

Java 比较两个包含满足 equals() 的同一对象的不同实例的集合

javascript - 为什么我在使用这个数组时会得到 NaN ?

java - 为什么 Collections 实用程序类在 Java 中没有 Iterator 方法?

python - 如何访问列表元素

python - 为什么 g.append(l.pop()) 返回 l 的后半部分但 l 只有前半部分

java - 为什么我的 eclipse 不生成 R.java 文件?

ios - 加入自定义对象数组

arrays - 当应用程序重新启动时,数组不会保存。持久数据的问题