java中List和Array相互轉換


List to Array

  List 提供了toArray的接口,所以可以直接調用轉為object型數組

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

  上述方法存在強制轉換時會拋異常,下面此種方式更推薦:可以指定類型

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

Array to List

  最簡單的方法似乎是這樣

復制代碼
String[] array = {"java", "c"}; List<String> list = Arrays.asList(array); //但該方法存在一定的弊端,返回的list是Arrays里面的一個靜態內部類,該類並未實現add,remove方法,因此在使用時存在局限性

public static <T> List<T> asList(T... a) {
// 注意該ArrayList並非java.util.ArrayList
// java.util.Arrays.ArrayList.ArrayList<T>(T[])
return new ArrayList<>(a);
}

復制代碼

解決方案:

  1、運用ArrayList的構造方法是目前來說最完美的作法,代碼簡潔,效率高:List<String> list = 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、運用Collections的addAll方法也也是不錯的解決辦法

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

Array or List 分隔

  其實自己實現一個分隔list或者數組的方法也並不復雜,但強大的第三方庫自然提供的有此類似的功能

// org.apache.commons.lang3.StringUtils.join(Iterable<?>, String)
StringUtils.join(list, ",")
// org.apache.commons.lang3.StringUtils.join(Object[], String) StringUtils.join(array, ",")
原文地址;https://www.cnblogs.com/goloving/p/7740100.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM