首页 > 解决方案 > Is there a way I can check if any of the objects in an ArrayList have an object of a specific class?

问题描述

Assuming I have a class hierarchy where Monkey, Chimp, and Ape classes all inherit from an Animal Class. I now have an ArrayList where some random number of monkeys/chimps/apes are stored inside. Is there a function that can check if any Monkeys exist in that arraylist? Right now I have

for (Animal animal1 : Enclosure.HABITABLE_ANIMALS)
     {
       if (animal.getClass().equals(animal1.getClass()))
          {
                    count++;
          }
     }

and if the count is greater than 0 it returns true (in this code you HABITABLE_ANIMALS is the arraylist of animals, and animal is the Monkey) surely there is a more efficient and better way of doing this

标签: java

解决方案


There is no more efficient way to do this unfortunately, since you'll need to go through the whole List anyway (time complexity: O(n))

However, there might be a more expressive way of doing it using Stream (but it adds the overhead of creating a Stream).

If expressiveness is more important than performance, I'd suggest to go for this solution

Enclosure.HABITABLE_ANIMALS
         .stream()
         .anyMatch(animal.getClass()::isInstance)

推荐阅读