分享

数组转集合后使用add方法异常&处理后可以使用add的正确操作

 windxn 2018-02-26

通常很多人为了操作方便喜欢把数组转换成集合再操作,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);


顺便回顾下数组与集合的一些区别:

  • 数组声明了它容纳的元素的类型,而集合不声明。这是由于集合以object形式来存储它们的元素。

  • 一个数组实例具有固定的大小,不能伸缩。集合则可根据需要动态改变大小。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多