如何区分同一抽象类的子类

时间:2017-10-20 01:14:08

标签: java class arraylist instanceof

想象一下,我有一个名为Car的课程和一系列像BMW,FORD等一样延伸汽车的子类。所以我有这个汽车的ArrayList,我试图将这个ArrayList中的每个对象分成不同的ArrayLists,每个品牌一个。我听说使用实例不是一个好习惯,所以我不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

我真的不知道如何解决这种多态性问题,但我建议不要使用instanceof而是使用Map代替汽车的类别和汽车列表参数。

在这种情况下,代码应该类似于:

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
}

希望能帮助你。

答案 1 :(得分:-1)

Java 8收集器分组在上面的情况下很有用

https://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/