【问题标题】:how to differentiate subclasses from the same abstract class如何区分同一个抽象类的子类
【发布时间】:2018-04-01 03:35:32
【问题描述】:

想象一下,我有一个名为 Car 的类和一堆扩展汽车的子类,如 BMW、FORD 等。所以我有这个 ArrayList 的汽车,我试图将这个 ArrayList 中的每个对象分离到不同的 ArrayLists,每个品牌一个。我听说使用 instance of 不是一个好习惯,所以我不知道该怎么做。

【问题讨论】:

  • “我听说使用实例不是一个好习惯,所以我不知道该怎么做。”是什么意思。您可以在基类中添加一个名为 Model 的属性。然后,您将使用此属性从列表中提取对象。我会亲自做类似 myobjects.OfType() ...
  • @Seb 我的老师不是我们使用实例的粉丝。我想过添加一个属性,但我想使用多态来解决这个问题。
  • 在子类设置的基类上放置一个受保护的模型字段,然后使用该字段对对象进行排序使用多态性来解决问题。

标签: java class arraylist instanceof


【解决方案1】:

我真的不知道如何解决这种多态性使用,但我建议不要使用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
}

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    Java 8 收集器分组依据在上述情况下很有用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 2018-06-28
      • 2023-03-07
      • 2019-08-24
      • 1970-01-01
      • 2012-11-15
      相关资源
      最近更新 更多