Imagine I have a class named Car and a bunch of subclasses that extend car like BMW,FORD,etc. So I have this ArrayList of cars and i am trying to separate each object in this ArrayList to diferent ArrayLists, one for each brand. I heard that using instance of is not a good practice so I have no idea how to do this.
Asked
Active
Viewed 319 times
0
-
1What do you mean by " I heard that using instance of is not a good practice so I have no idea how to do this.". You could add a property called Model in your base class. Then you would extract objects from your list using this property. I would personnaly do something like myobjects.OfType
() ... – Oct 20 '17 at 01:16 -
1[You could implement the visitor pattern](https://stackoverflow.com/questions/29458676/how-to-avoid-instanceof-when-implementing-factory-design-pattern/29459571#29459571) – Vince Oct 20 '17 at 01:18
-
@Seb my teachers are not fans of us using instance of. I thought about adding a property but I would like to use polymorphism to solve this problem. – Tiago Gomes Oct 20 '17 at 01:19
-
https://stackoverflow.com/questions/20589590/why-not-use-instanceof-operator-in-oop-design – alejandrogiron Oct 20 '17 at 01:21
-
2Putting a protected model field on the base class that the subclasses set and then using that field to sort the objects _is_ using polymorphism to solve the problem. – astidham2003 Oct 20 '17 at 01:34
2 Answers
0
I don't really know how to solve this polymorphism use, but i propose to not use instanceof
and use a Map
instead, with the class of the car and the list of the cars as arguments.
In this case, the code should look something like :
private static Collection<List<Car>> separateCars(List<Car> cars) {
Map<Class, List<Car>> result = new HashMap<>(); // creating the empty map with results
for (Car car : cars) { // iterating over all cars in the given list
if (result.containsKey(car.getClass())) { // if we have such car type in our results map
result.get(car.getClass()).add(car); // just getting the corresponding list and adding that car in it
} else { // if we faced with the class of the car that we don't have in the map yet
List<Car> newList = new ArrayList<>(); // creating a new list for such cars
newList.add(car); // adding this car to such list
result.put(car.getClass(), newList); // creating an entry in results map with car's class and the list we just created
}
}
return result.values(); // returning only the lists we created as we don't need car's classes
}
Hope that will help you.

pirs
- 2,410
- 2
- 18
- 25

s.pasynkov
- 1
- 2
-2
Java 8 Collectors grouping by can be useful in above case
https://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/

Code_Eat_Sleep
- 303
- 2
- 6