Java List and Array transformation

List to Array

List toArray provides interface, so you can directly call into object array

List<String> list = new ArrayList<String>();
Object[] array=list.toArray();

Flip a cast method described above in the presence of anomalies, such embodiment also recommend the following: you can specify the type

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

Array to List

The easiest way seems to be so

String [] Array = { "Java", "C"}; 
List <String> list = Arrays.asList (Array); 
// but there are some drawbacks to this method, the list returned by a static inner class Arrays inside, this class does not implement add, remove method, there is a limitation in the use of 

public static <T> List <T> asList (A T ...) { 
// Note that this is not ArrayList of java.util.ArrayList 
// Java. util.Arrays.ArrayList.ArrayList <T> (T []) 
    return new new the ArrayList <> (A); 
}

 

solution:

1, the construction method using ArrayList is at present the most perfect way, the code is simple and efficient: List <String> List = new new ArrayList <String> (Arrays.asList (Array));

List<String> list = new ArrayList<String>(Arrays.asList(array));

//ArrayList构造方法源码
public ArrayList(Collection<? extends E> c) {
    elementData = c.toArray();
    size = elementData.length;
    // c.toArray might (incorrectly) not return Object[] (see 6260652)
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, size, Object[].class);
}

  

2, the use of Collections of addAll methods is also a good solution

List<String> list = new ArrayList<String>(array.length);
Collections.addAll(list, array);

 

https://www.cnblogs.com/goloving/p/7740100.html

Guess you like

Origin www.cnblogs.com/Allen-rg/p/11365712.html