Why do I get an UnsupportedOperationException when trying to remove an element from a List?

后端 未结 17 2008
后悔当初
后悔当初 2020-11-22 07:43

I have this code:

public static String SelectRandomFromTemplate(String template,int count) {
   String[] split = template.split(\"|\");
   List         


        
17条回答
  •  忘了有多久
    2020-11-22 07:54

    The issue is you're creating a List using Arrays.asList() method with fixed Length meaning that

    Since the returned List is a fixed-size List, we can’t add/remove elements.

    See the below block of code that I am using

    This iteration will give an Exception Since it is an iteration list Created by asList() so remove and add are not possible, it is a fixed array

    List words = Arrays.asList("pen", "pencil", "sky", "blue", "sky", "dog"); 
    for (String word : words) {
        if ("sky".equals(word)) {
            words.remove(word);
        }
    }   
    

    This will work fine since we are taking a new ArrayList we can perform modifications while iterating

    List words1 = new ArrayList(Arrays.asList("pen", "pencil", "sky", "blue", "sky", "dog"));
    for (String word : words) {
        if ("sky".equals(word)) {
            words.remove(word);
        }
    }
    

提交回复
热议问题