Arrays.asList(new int[]{1,2,3})和Arrays.asList(new Integer[]{1,2,3})

Arrays.asList(new int[]{1,2,3});
Arrays.asList(new Integer[]{1,2,3});

这两行代码的返回值是不一样的。

看源码的话,该方法是是这样的

public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
}

既然是一个可变长度,那么传入int[]和Integer[]进去,肯定是将数组平铺。

那么int[]和Integer[]的中的元素类型是怎么样?一个是int,一个是Integer?

但是好像没有int这个类吧?虽然有着int.class的代码写法倒是了。

结果是这样的

     int[] a = new int[] {1,2,3,4,5,6,7,8};
        Integer[] b = new Integer[] {1,2,3,4,5,6,7,8};
        List<int[]> ints1 = Arrays.asList(a);
        List<Integer> list = Arrays.asList(b);

需要注意asList返回的不是java.util包下的ArrayList,而是Arrays类中的静态内部类。所以没有重写remove之类的方法,调用其父类的方法。

public E remove(int index) {
        throw new UnsupportedOperationException();
    }

抛出不支持运算异常

原文地址:https://www.cnblogs.com/woyujiezhen/p/14159318.html