javacollectionsconcurrentmodificationunsupportedoperation

UnsupportedOperationException vs ConcurrentModificationExcetion


I have a code that adds data to a list. What I do not understand is why the UnsupportedOperationException is thrown in one case and ConcurrentModificationException in the other. I am adding data in list in both the case and then trying to remove list data while iterating over the list. What i have read so far is that whenever any modification is made to fail- fast collection,ConcurrentModificationException is thrown. So why this different behavior in both these cases?

  List<String> animalList = new ArrayList<>();
        animalList.add("cat");
        animalList.add("dog");
        animalList.add("bear");
        animalList.add("lion");

        Iterator<String> iter = animalList.iterator();

        while(iter.hasNext()){
            String animal = iter.next();
            System.out.println(animal);
            animalList.remove(3);
        }

This code throws ConcurrentModificationException

String[] strings = { "Java", "Honk", "Test" };

        List<String> list = Arrays.asList(strings);


        Iterator<String> iterator = list.iterator();

        while(iterator.hasNext()){
            String name = iterator.next();
            System.out.println(name);
            list.remove(3);
        }

while this one throws UnsupportedOperationException


Solution

  • For the code block, where you get ConcurrentModificationException , you get that exception because you created an iterator on List then removing directly from list from within loop so iterator has issues. You should use remove() method of iterator itself - Iterator.remove().

    You should directly remove an element from list when removing from outside iterator loop. See this another SO Question

    In second case, with Arrays.asList , you get a List but actual list object might not be an ArrayList and remove(int index) operation is optional at List interface. See this

    All in all, as far as UnsupportedOperationException is concerned, in first case you are guaranteed to working with an ArrayList and for that class, remove operation is supported , See this

    For second case, you can't be so sure. Refer documentation of Arrays.asList where it says that returned list of fixed size so certain operations are not supported.