Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retain all instances of of a single subclass from a general ArrayList

Tags:

java

I'm having a problem and I can't figure out a clean solution.

I have this superclass "Creature" with subclasses "Human" and "Zombie" I have constructed a series of humans and zombies and saved them in an ArrayList Now I want to get the subArrayList that only contains the constructed humans. I thought I could use the "retainAll" but it turns out it doesn't do what I thought it would do.

Any suggestions how to create a new ArrayList with only the objects of subclass Zombie in it?

like image 517
user1193435 Avatar asked Feb 22 '23 14:02

user1193435


1 Answers

You can use the instanceof operator. Try this code:

List<Human> humans = new ArrayList<Human>();
for (Creature creature : creatures) {
    if (creature instanceof Human) {
        humans.add((Human) creature);
    }
}
like image 193
Mairbek Khadikov Avatar answered Feb 24 '23 04:02

Mairbek Khadikov