Convert list to array in Java [duplicate]

2018-12-31 10:27发布

This question already has an answer here:

How can I convert a List to an Array in Java?

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.

12条回答
十年一品温如言
2楼-- · 2018-12-31 10:46

This is works. Kind of.

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

Then the main method.

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]);
}
查看更多
千与千寻千般痛.
3楼-- · 2018-12-31 10:47

An alternative in Java 8:

String[] strings = list.stream().toArray(String[]::new);
查看更多
墨雨无痕
4楼-- · 2018-12-31 10:53

Either:

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

or:

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

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
查看更多
人气声优
5楼-- · 2018-12-31 10:55

You can use toArray() api as follows,

ArrayList<String> stringList = new ArrayList<String>();
stringList.add("ListItem1");
stringList.add("ListItem2");
String[] stringArray = new String[stringList.size()];
stringArray = stringList.toArray(stringList);

Values from the array are,

for(String value : stringList)
{
    System.out.println(value);
}
查看更多
冷夜・残月
6楼-- · 2018-12-31 10:57

Best thing I came up without Java 8 was:

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

If anyone has a better way to do this, please share :)

查看更多
不再属于我。
7楼-- · 2018-12-31 10:59

I think this is the simplest way:

Foo[] array = list.toArray(new Foo[0]);
查看更多
登录 后发表回答