UnsupportedOperationException on Collection

流过昼夜 提交于 2021-01-20 17:33:47

问题


While studying the Collection API, we find that some methods (add, remove,...) may throw a java.lang.UnsupportedOperationException if the current implementation of the Collection does not support those functionalities.

Is there,actually, in the JDK, a concrete Collection that does not support those methods ?

Thanks a lot for your answers.


回答1:


The obvious examples are the implementations returned from, say, Collections.unmodifiableCollection() and other similar methods. Methods that would change the Collection throw this exception.




回答2:


Apart from the collections returned by the Collections.unmodifiable* methods, there are a couple more of interesting cases where UnsupportedOperationException is actually thrown:

  • the collection views of a Map, accessed via entrySet(), keySet() and values() can have elements removed but not added,
  • the list view returned by Arrays.asList can have elements neither added nor removed,
  • moreover, the objects obtained from the Collections.empty* and Collections.singleton* methods are also marked as "immutable", so - although it is not explicitly stated in the API docs - I suppose these throw the exception as well on attempts to modify them.



回答3:


Normally when you create a list like List<String> sample=Collections.emptyList();. The List sample will be created as a Collections.unmodifiableCollection().

  • So the list sample does not support dynamic list operations. You can only assign another list to this list using assignment operator. Eg>

    List<String> ls=new ArrayList<String>();
    ls.add("one");
    ls.add("Three");
    ls.add("two");
    ls.add("four"); 
    sample = ls;
    
  • For dynamic list operations you should have a syntax like List<String> sample= new ArrayList<String>();. In this list you can perform sample.add(), sample.addAll() etc...




回答4:


Yes. For example when you call Collections.unmodifiableList(list), the returned list does not support add(..)

These collections, however, are mostly private classes which are not exposed an an API, so you cannot instantiate them.



来源:https://stackoverflow.com/questions/2887590/unsupportedoperationexception-on-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!