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?
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With