1 数组转list可以使用Arrays.asList(),用ArrayList的构造方法新建一个arraylist
如下:
class="java">ArrayList(E[] array) { if (array==null) throw new NullPointerException(); a = array; }
?因此使用前需要null判断
此ArrayList是Arrays的一个内部类,不是java.util.ArrayList,未研究
?
2 ?list转array list接口有两个重载的monospace; font-size: 1em; line-height: 1.5;">toArray(),toArray(T[] a)
如果使用toArray()等同于toArray(new Object[0])
// List转换为数组 public static String[] list2Array(List<String> list) { String[] strs1 = list.toArray(new String[list.size()]); return strs1; }
?实验表明不指定长度也可以,如
names.toArray(new String[]{})
?网上搜的
?toArray()正确使用方式如下:
??????? 1)??Long[] l = new Long[<total size>];
????????? ?? ?list.toArray(l);
??????? 2)? Long[] l = (Long []) list.toArray(new Long[0]);
?????? ?3) ?Long [] a = new Long[<total size>];
???????? ??? ?Long [] l = (Long []) list.toArray(a);
未进一步实验
?
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ArrayUtil { /** * 数组转换为List,Arrays.asList可能抛出空指针异常,此方法不会 * @param strs * @return */ public static List<String> array2List(String... strs) { if (null==strs||strs.length<1) { return new ArrayList<String>(0); } List<String> list = Arrays.asList(strs); return list; } // List转换为数组 public static String[] list2Array(List<String> list) { String[] strs = list.toArray(new String[list.size()]); return strs; } public static void main(String[] args) { String a="a"; String b="b"; String c="c"; List<String> list=array2List(a,b,c); // List<String> list=array2List(new String[]{"aa","bb","cc"}); for (String string : list) { System.out.println(string); } } }
?