How to save all instances of one subclass from a common ArrayList array

I have a problem and I canโ€™t figure out how to do this.

I have this Creature superclass with subclasses Man and Zombies. I built a series of people and zombies and saved them in an ArrayList. Now I want to get a subArrayList that contains only constructed people. I thought I could use "keepAll", but it turns out that it does not do what I thought it would do.

Any suggestions on how to create a new ArrayList with Zombie subclass objects in it?

+4
source share
5 answers

You can use instanceof operator. Try this code:

 List<Human> humans = new ArrayList<Human>(); for (Creature creature : creatures) { if (creature instanceof Human) { humans.add((Human) creature); } } 
+3
source

With Guava :

 List<Zombie> zombies = Lists.newArrayList(Iterables.filter(creatures, Zombie.class)); 
+3
source

You need to iterate through the elements, use instanceof and build a new arraylist. For this, I would use the Google Guava library

+1
source

take a look at instanceof operator

Note. This is probably the smell of code , if you need to filter the list based on a specific type of instance - if you give more details about what you are trying to do - maybe there is a better way to achieve it, and refactoring your code

+1
source

I don't think there is a very clean way to do this, only with instanceof and drops, as mentioned in other answers.

If possible, I suggest keeping separate lists of each type and merging lists only when you need all Creatures.

0
source

Source: https://habr.com/ru/post/1395114/


All Articles