本文主要是介绍记渣渣踩坑系列 -使用Arrays.asList 将数组array 转为List 踩坑记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*** zhazhahao使用 Arrays.asList:将数组转为List集合引发的思考。* * 问题1、Arrays.asList 方法传入基本类型数组(int[])和包装类型数组(Integer[])* 返回数据格式是否都为List<int>或List<Integer>?* * 问题2、返回的集合List 是否是传统意义上的集合:是否做add和remove删除动作* * TestZhaZhaAsList * @author shiyuqiong * @date 2018年9月19日 上午10:40:44**/
public class TestZhaZhaAsList {public static void main(String[] args) {int[] intList={1,2};// eg1:System.out.println(JSONObject.toJSONString(Arrays.asList(intList)));// eg2:输出 [[1,2]]Integer[] integerList={1,2};// eg3:System.out.println(JSONObject.toJSONString(Arrays.asList(integerList)));// eg4:输出 [1,2]testIn(intList);//5 输出什么?testIn(integerList);//6 输出什么?}public static <T> void testIn(T...args){System.out.println(JSONObject.toJSONString(args));}
}
/*** 答一:在运行代码时候回发现 标注为2的代码行输出结构为 [[1,2]],* 代码4:位置输出为 [1,2],那么为什么int[]基本类型数组转为List会输出* 结果为一个二维数组?* 看Arrays.asList(T... a) ,发现asList方法参数为 “泛型可变参数类型”,* 经编译器编译进行类型擦除后变为: Arrays.asList(Object[] a)。* 然而,int[] 不能被转为 Object[]数组类型。 * 因为 auto boxing 和 unboxing 是针对 基本类型和其对应的封装类型来讲。* 这时候eg2 这个位置, intList 参数会被当成 Object[] 对应中储存的* 对象:Arrays.asList(Object[] a) a 变成 int[][],* 以至于Arrays.asList返回为 List<int[]> 。* * Integer[] 可转为Object[] 所以此时Arrays.asList(Object[] a) * a 的实际数据类型了Integer[] 数组类型* * * 答二: 对于第二个问题可见文档(* * 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}.* )意思是说:asList返回是一个固定长度的List 。该方法主要是将array转为List * 可使用 collection中对应的api。* 且这里Arrays.asList返回ArrayList 其实是java.util.Arrays.ArrayList.ArrayList * 并不是java.util.ArrayList<E> 。* 之所以 asList 返回的 集合能够使用collection API。:* java.util.Arrays.ArrayList. ArrayList<E> extends AbstractList<E> * implements List<E>, RandomAccess, Cloneable, java.io.Serializable* * * */
这篇关于记渣渣踩坑系列 -使用Arrays.asList 将数组array 转为List 踩坑记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!