0

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


Abhishek
  • 650
  • 1
  • 8
  • 31
  • Why not expecting `RuntimeException`, like what would you do differently in a dynamic way? probably nothing.. – Most Noble Rabbit May 27 '21 at 08:31
  • @PradeepSimha no this does not answers my question. My question was not to avoid ConcurrentModificationException. My question was like why i am not getting ConcurrentModificationException(i was expective this exception in my code) but instaed i was getting unsopportedRuntimeException – Abhishek May 27 '21 at 08:35
  • The answer to your last question is: You cannot do it. Explained in the first duplink. You cannot add or remove elements in a fixed length list. – Stephen C May 27 '21 at 08:37

1 Answers1

3

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);
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26