2017-10-20 3 views
0

私は、Carという名前のクラスと、BMW、FORDなどの車を拡張するサブクラスの束があるとします。だから私は車のこのArrayListを持って、私はこのArrayList内の各オブジェクトを別のArrayLists、各ブランドごとに1つに分けようとしています。私はインスタンスの使用は良い練習ではないと聞きましたので、私はこれをどうやって行うのか分かりません。サブクラスを同じ抽象クラスから区別する方法

+1

上記の場合に役立ちます。 "基本クラスにModelというプロパティを追加できます。次に、このプロパティを使用してリストからオブジェクトを抽出します。私は個人的にmyobjects.OfTypeのようなものを行います。()... – Seb

+1

[訪問者パターンを実装することができます](https://stackoverflow.com/questions/29458676/how-to-avoid-instanceof-when-implementing-factory -design-pattern/29459571#29459571) –

+0

@Seb私の先生は、のインスタンスを使用して私たちのファンではありません。私はプロパティを追加することを考えましたが、この問題を解決するために多態性を使用したいと考えています。 –

答えて

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 
} 

希望:

この場合、コードは次のようになります。グループ化

関連する問題