`
xfxlch
  • 浏览: 162092 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Caused by: java.lang.UnsupportedOperationException 解决方案

    博客分类:
  • Java
 
阅读更多
背景:

今天在跑一个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)却不报错。
参考如下代码:

public static void main(String[] args) {
		Person person  = new User();
		List<Person> list = new ArrayList<Person>();
		list.add(person);
		
		String s[]={"ram","ganesh","paul"};
		List li=Arrays.asList(s);
		li.remove(0);
		
		
		Map map =new HashMap();
		map.put("1","Ram");
		map.put("2","Ganesh");
		map.put("3","Paul");
		System.out.println(map);
		
		map.remove("1");

		System.out.println(map);
	}



现在知道UnsupportedOperationException 异常怎么改了吧:)

----EOF----
分享到:
评论
1 楼 xfxlch 2015-10-26  
http://stackoverflow.com/questions/13972633/jpa-mapping-for-one-to-many-with-inheritance-mapping

相关推荐

Global site tag (gtag.js) - Google Analytics