UnsupportedOperationException on Collection

后端 未结 4 947
醉酒成梦
醉酒成梦 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:35

    Normally when you create a list like List 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 ls=new ArrayList();
      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 sample= new ArrayList();. In this list you can perform sample.add(), sample.addAll() etc...

提交回复
热议问题