您的当前位置:首页Arrays.asList(s)使用注意

Arrays.asList(s)使用注意

2024-12-13 来源:哗拓教育

1,参数为null
当 Arrays.asList(null)//会报错:java.lang.NullPointerException

2,asList操作基本数据类型的数组,直接输出返回值为地址

int[] array02 = new int[]{1,2,3,4,5,6};
//Object list02 = Arrays.asList(array02);//返回值不是List<Integer>
System.out.println(Arrays.asList(array02));//输出值为地址

3,asList操作String类型的数组,返回的List大小固定,不能使用remove/add方法

String[] array = new String[]{"1","2","3","4","5","6"};
System.out.println(Arrays.asList(array));
//sList.add("1");//报错:java.lang.UnsupportedOperationException
//sList.remove("1");//报错:java.lang.UnsupportedOperationException
//原因:返回的ArrayList并不是ArrayList类,而是Arrays的内部类

Arrays.asList(array)调用如下方法:

/**
     * 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);
    }

显示全文