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


3
  • Why not expecting RuntimeException, like what would you do differently in a dynamic way? probably nothing.. Commented May 27, 2021 at 8: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 Commented May 27, 2021 at 8: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. Commented May 27, 2021 at 8:37

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. my first questions is answered
Edited to also address the second part of your question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.