Arrays.asList(s)使用注意

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

参考:http://javapub.iteye.com/blog/1551604

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 9,713评论 0 16
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,518评论 19 139
  • Java 语言支持的类型分为两类:基本类型和引用类型。整型(byte 1, short 2, int 4, lon...
    xiaogmail阅读 5,176评论 0 10
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,958评论 18 399
  • java笔记第一天 == 和 equals ==比较的比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量...
    jmychou阅读 5,400评论 0 3