zoukankan      html  css  js  c++  java
  • list remove踩的坑

    背景: 

    今天在跑一个UnitTest,跑的过程中想在list的最后多加一个Element,即 List.add(Element e),多测试一条数据。 可是在run的过程中,却一直在抛:Caused by: java.lang.UnsupportedOperationException。 我对这个异常不了解,凭借自己的有限知识,都不能解决这个问题/最后google到了答案,先上link: http://craftingjava.blogspot.com/2012/06/how-to-resolve-unsupportedoperationexce.html。 

    方案: 
    首先要知道这个是什么: 
    了解什么是UnsupportedOperationException, 只有知道了它,我们才能更好的来解决这个问题。 官方有个解释是: 
    Throws: 
    UnsupportedOperationException - if the add operation is not supported by this list, 
    也就是说add操作对此list来说,不被支持了。 那么什么情况才不被支持呢? 

    也就是为什么: 
    UnsupportedOperationException异常的发生通常都是在集合框架中,例如:List,Queue,Set,Map等等。针对这些集合,我们要知道它是分成不同的type的,一类就可以被修改的,一个就是不能被修改的(就是相当于这个值是固定的,不能被加减)。 也就是link文件里提到的view的概念, 也就是view是read-only  的。 

    引用
    A view is a read-only format of the collections,which means that through view we can  traverse the collections and even we can retrieve values.But if you try to modify the collection using view object  this will cause an UnsupportedOperationException to be thrown.


    也就是说Lists.asList()得到的list是跟new ArrayList() 是不一样的,new出来的List是可以随意add,remove的但是Lists.asList得到的却不能这么玩。这个要看具体的api,例如: List是不能用List.remove(index) 来操作的,但是Map.remove(Key)却不报错。 
    参考如下代码: 

    Java代码  收藏代码
    1. public static void main(String[] args) {  
    2.         Person person  = new User();  
    3.         List<Person> list = new ArrayList<Person>();  
    4.         list.add(person);  
    5.           
    6.         String s[]={"ram","ganesh","paul"};  
    7.         List li=Arrays.asList(s);  
    8.         li.remove(0);  
    9.           
    10.           
    11.         Map map =new HashMap();  
    12.         map.put("1","Ram");  
    13.         map.put("2","Ganesh");  
    14.         map.put("3","Paul");  
    15.         System.out.println(map);  
    16.           
    17.         map.remove("1");  
    18.   
    19.         System.out.println(map);  
    20.     }  



    现在知道UnsupportedOperationException 异常怎么改了吧:) 
  • 相关阅读:
    powerdesigner 使用心得 comment、name
    idea 从git上checkout项目下来,project没有文件目录结构
    关于freemarker 空变量的接收以及类型转换 笔记
    关于indexof和substring经常记不住的点
    Intellij IDEA快捷键
    oracle 修改服务端字符集编码
    个人作业——软件工程实践总结&个人技术博客
    如何设置标签云
    前端框架的部署
    个人作业——软件评测
  • 原文地址:https://www.cnblogs.com/dpains/p/10335619.html
Copyright © 2011-2022 走看看