如何将列表转换为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。


当前回答

试试这个:

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

Object[] ol = list.toArray();

其他回答

在没有Java 8的情况下,我想到的最好的事情是:

public static <T> T[] toArray(List<T> list, Class<T> objectClass) {
    if (list == null) {
        return null;
    }

    T[] listAsArray = (T[]) Array.newInstance(objectClass, list.size());
    list.toArray(listAsArray);
    return listAsArray;
}

如果有人有更好的方法,请分享:)

以下(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. The toArray call does not care about the size or contents of the given array - it only needs its type. It would have been better if it took an actual Type in which case "Foo.class" would have been a lot clearer. 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.

这是可行的。种。

public static Object[] toArray(List<?> a) {
    Object[] arr = new Object[a.size()];
    for (int i = 0; i < a.size(); i++)
        arr[i] = a.get(i);
    return arr;
}

然后是主要方法。

public static void main(String[] args) {
    List<String> list = new ArrayList<String>() {{
        add("hello");
        add("world");
    }};
    Object[] arr = toArray(list);
    System.out.println(arr[0]);
}

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

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

对于ArrayList,以下工作:

ArrayList<Foo> list = new ArrayList<Foo>();

//... add values

Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);