今天在跑一個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);
- }