通常很多人为了操作方便喜欢把数组转换成集合再操作,jdk也刚好有这样的方法,Arrays.asList ,我们看看他的内部实现
/** * Returns a fixed-size list backed by the specified array. (Changes to * the returned list 'write through' to the array.) This method acts * as bridge between array-based and collection-based APIs, in * combination with {@link Collection#toArray}. The returned list is * serializable and implements {@link RandomAccess}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> * List<String> stooges = Arrays.asList('Larry', 'Moe', 'Curly'); * </pre> * * @param <T> the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */ @SafeVarargs @SuppressWarnings('varargs') public static <T> List<T> asList(T... a) { return new ArrayList<>(a); }
我们通过方法上面的描述可以得知,通过这样调用将数组转换成集合,返回的集合大小是固定的,因此往里面再添加元素肯定报错了。 那么解决这个问题的正确姿势是什么,稍微修改下即可: //错误姿势 List<String> list1 = Arrays.asList('1', '2', '3'); List<String> list2 = Arrays.asList('4', '5', '6'); list1.addAll(list2);
//正确姿势 List<String> list3 = new ArrayList<>(Arrays.asList('1', '2', '3')); List<String> list4 = new ArrayList<>(Arrays.asList('1', '2', '3')); list3.addAll(list4);
顺便回顾下数组与集合的一些区别:
|