zoukankan      html  css  js  c++  java
  • 【坑】不要使用各种框架提供的内部List

    为了代码简洁有时我们会使用一些框架提供的工具类。如

    import org.apache.commons.collections.ListUtils;
    package java.util.Collections;
    
     List<String> strList = ListUtils.EMPTY_LIST;
    
    List<String> strList1 = Collections.emptyList();
    

    实际该空List是个内部类,没有实现add等方法,使用时会报错。

    
     /**
        * {@inheritDoc}
        *
        * <p>This implementation always throws an
        * {@code UnsupportedOperationException}.
        *
        * @throws UnsupportedOperationException {@inheritDoc}
        * @throws ClassCastException            {@inheritDoc}
        * @throws NullPointerException          {@inheritDoc}
        * @throws IllegalArgumentException      {@inheritDoc}
        * @throws IndexOutOfBoundsException     {@inheritDoc}
        */
       public void add(int index, E element) {
           throw new UnsupportedOperationException();
       }
    

    又如,使用

    arrays.aslist(T...a)
    

    再进行add操作,同样会报该错。
    https://www.2cto.com/kf/201806/751606.html

    因此,还是老老实实使用下面方式初始化List

    List<String> strList=new ArrayList<>();
    

    或者确认工具类提供的是java的ArrayList再使用。

  • 相关阅读:
    poj 2104 C
    2015 百度之星初赛 1 2 2015ACM/ICPC亚洲区上海站 codeforces 851
    3.10补
    3.9补
    3.8补
    3.6补
    3.5补
    3.4补
    3.3补
    2.35补
  • 原文地址:https://www.cnblogs.com/z00377750/p/10809006.html
Copyright © 2011-2022 走看看