Crookedgray
Crookedgray

Reputation: 3

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

Upvotes: 0

Views: 53

Answers (2)

Richard Woods
Richard Woods

Reputation: 2283

You dont need to keep counting after you encounter your first Monkey. Also instanceof might be faster than calling Class.equals(), assuming you're OK with subtypes of Monkey to count.

boolean hasMonkey(Iterable<? extends Animal> animals){
   for (Animal animal : animals) 
      if (animal instanceof Monkey) 
         return true;
   return false;
}

If by efficient your meant 'concise' the streams API has the method anyMatch

animals.stream().anyMatch(i -> i instanceof Monkey);

Upvotes: 1

Yassin Hajaj
Yassin Hajaj

Reputation: 22005

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)

Upvotes: 1

Related Questions