Search code examples
javalistarraylistcollectionsconcurrentmodification

Expecting ConcurrentModificationException but getting UnsupportedException


I have a list of Animals. My target is to remove only dogs from the list. How to do that?

I have the below code for the same

Dog d1= new Dog("Dog 1");
        Dog d2= new Dog("Dog 2");
        Dog d3= new Dog("Dog 3");
        
        Cat c1= new Cat("Cat 1");
        Cat c2= new Cat("Cat 2");
        
        List<Animal> al= Arrays.asList(d1,d2,c1,c2,d3);
        for(Animal eachlist : al)
        {
            if(eachlist instanceof Dog)
            {
                al.remove(eachlist);
            }
            System.out.println(eachlist.toString());
        }

Points

1.I am expecting al.remove() to throw ConcurrentModificationException but it throws me UnsoppertedException. Why? 2. How to actually remove all the dogs from the list



Solution

  • This is caused by using Arrays.asList. This uses a limited List implementation that reuses the array you specified as parameter. Seeing as an array cannot shrink in size, neither can this list implementation.

    To get the exception you're expecting, try using a different List implementation such as ArrayList, for instance by passing your list to the constructor of ArrayList:

    List<Animal> al = new ArrayList<>(Arrays.asList(d1,d2,c1,c2,d3));
    

    To then remove all instances of dog:

    al.removeIf(a -> a instanceof Dog);