UnsupportedOperationException on Collection

后端 未结 4 943
醉酒成梦
醉酒成梦 2021-02-05 03:13

While studying the Collection API, we find that some methods (add, remove,...) may throw a java.lang.UnsupportedOperationException

4条回答
  •  执念已碎
    2021-02-05 03:38

    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.

提交回复
热议问题