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 异常怎么改了吧:) 
相关文章
相关标签/搜索