在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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章