在Java中将列表转换为数组[重复]

2023-12-08

我怎样才能转换List to an Array在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);  

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


Either:

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

or:

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);

Update:

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

来自 JetBrains Intellij Idea 检查:

有两种方式将集合转换为数组:使用 预先确定大小的数组(例如c.toArray(new String[c.size()])) 或者 使用空数组(例如c.toArray(新字符串[0]).

在 建议使用预先确定大小的数组的旧 Java 版本,因为 反射调用是创建适当大小的数组所必需的 速度相当慢。然而,由于 OpenJDK 6 的最新更新,此调用 被内在化,使得空数组版本的性能 与预先设定的尺寸相比,相同,有时甚至更好 版本。另外,传递预先确定大小的数组对于并发或 同步收集作为数据竞争是可能的size and toArray调用可能会导致额外的空值 在数组的末尾,如果集合同时收缩 在操作过程中。

这项检查允许遵循 统一风格:要么使用空数组(推荐在 现代Java)或使用预先确定大小的数组(这可能会更快) 较旧的 Java 版本或基于非 HotSpot 的 JVM)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在Java中将列表转换为数组[重复] 的相关文章

随机推荐