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

本文翻译自:Convert list to array in Java [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

How can I convert a List to an Array in Java? 如何在Java中将List转换为Array

Check the code below: 检查以下代码:

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

I need to populate the array tiendas with the values of tiendasList . 我需要填充阵列tiendas用的值tiendasList


#1楼

参考:https://stackoom.com/question/eAJv/在Java中将列表转换为数组-重复


#2楼

Try this: 试试这个:

List list = new ArrayList();
list.add("Apple");
list.add("Banana");

Object[] ol = list.toArray();

#3楼

tiendas = new ArrayList<Tienda>(tiendasList);

All collection implementations have an overloaded constructor that takes another collection (with the template <T> matching). 所有集合实现都有一个重载的构造函数,它接受另一个集合(模板<T>匹配)。 The new instance is instantiated with the passed collection. 使用传递的集合实例化新实例。


#4楼

我认为这是最简单的方法:

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

#5楼

This (Ondrej's answer): 这(Ondrej的回答):

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

Is the most common idiom I see. 这是我看到的最常见的习语。 Those who are suggesting that you use the actual list size instead of "0" are misunderstanding what's happening here. 那些建议你使用实际列表大小而不是“0”的人误解了这里发生的事情。 The toArray call does not care about the size or contents of the given array - it only needs its type. toArray调用不关心给定数组的大小或内容 - 它只需要它的类型。 It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. 如果采用实际类型会更好,在这种情况下,“Foo.class”会更加清晰。 Yes, this idiom generates a dummy object, but including the list size just means that you generate a larger dummy object. 是的,这个成语生成一个虚拟对象,但包含列表大小只是意味着你生成一个更大的虚拟对象。 Again, the object is not used in any way; 同样,该对象不以任何方式使用; it's only the type that's needed. 它只是需要的类型。


#6楼

Java 8中的替代方案:

String[] strings = list.stream().toArray(String[]::new);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章