Arrays.asList()方法是Java中常见的将数组转换成列表的方式。
String[] myArray = { "Apple", "Banana", "Orange" };
List<String> myList = Arrays.asList(myArray);
List<String> myList = Arrays.asList("Apple","Banana", "Orange");
在使用Arrays.asList()时候,如果使用不好会有大坑。这里先提最重要的一点:Arrays.asList()转化的对象,可以遍历,不可以新增/删除。
坑1、传递数组不能为基本类型
int[] myArray = { 1, 2, 3 };
List myList = Arrays.asList(myArray);
System.out.println(myList.size());//1
System.out.println(myList.get(0));//数组地址值
System.out.println(myList.get(1));//报错:ArrayIndexOutOfBoundsException
int [] array=(int[]) myList.get(0);
System.out.println(array[0]);//1
Arrays.asList()的本质,底层还是数组,但表现的可以类似列表一样可以被遍历,查询。解决上述问题的最好的方式就是讲myArray变成对象数组。
Integer[] myArray = { 1, 2, 3 };
坑2、不允许使用remove/clear/add
查看源码可以了解到,Arrays.asList()返回的是一个不完整的内部类,并没有实现这些方法。很大原因就是设计者就是在底层设计的时候还是设计成数组,只是想让他能像列表一样方便遍历。
Integer[] myArray = { 1, 2, 3 };
List myList = Arrays.asList(myArray);
myArray[0]=100;
System.out.println(myList.get(0));//100
完全将数组转化成列表
一、傻瓜式
class Utils{
static <T> List<T> arrayToList(final T[] array) {
final List<T> l = new ArrayList<T>(array.length);
for (final T s : array) {
l.add(s);
}
return (l);
}
}
二、一般方法
List list = new ArrayList<>(Arrays.asList("a", "b", "c"))
三、stream方式(推荐)
List myList = Arrays.stream(myArray).collect(Collectors.toList());
//基本类型也可以实现转换(依赖boxed的装箱操作)
int [] myArray2 = { 1, 2, 3 };
List myList = Arrays.stream(myArray2).boxed().collect(Collectors.toList());
四、guava方式(推荐)
对于不可变集合,你可以使用ImmutableList类及其of()与copyOf()工厂方法:(参数不能为空)
List<String> il = ImmutableList.of("string", "elements"); // from varargs
List<String> il = ImmutableList.copyOf(aStringArray); // from array
对于可变集合,你可以使用Lists类及其newArrayList()工厂方法:
List<String> l1 = Lists.newArrayList(anotherListOrCollection); // from collection
List<String> l2 = Lists.newArrayList(aStringArray); // from array
List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs
五、 Apache Commons Collections(推荐)
List<String> list = new ArrayList<String>();
CollectionUtils.addAll(list, str);
原文来自:Github