2017-10-20 1 views
0

저는 Car라는 클래스와 BMW, FORD 등과 같은 자동차를 확장하는 서브 클래스를 가지고 있다고 상상해보십시오. 그래서 나는이 ArrayList의 자동차를 가지고 있고이 ArrayList의 각 객체를 각기 다른 ArrayLists로 분리하려고합니다. 인스턴스를 사용하는 것은 좋은 습관이 아니므로이 작업을 수행하는 방법을 모른다.하위 클래스를 동일한 추상 클래스와 구별하는 방법

+1

"나는의 인스턴스를 사용하는 것은 좋은 방법이 아닙니다 들었 위의 경우에 유용 할 수 있습니다 그래서 나는이 작업을 수행하는 방법을 모르겠어요. ". 기본 클래스에 Model이라는 속성을 추가 할 수 있습니다. 그런 다음이 속성을 사용하여 목록에서 개체를 추출합니다. 나는 personnaly와 같은 것을 할 것입니다. 객체 타입 () ... – 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 
} 

희망 :

이 경우, 코드가 같은 것을 보일 것입니다. 에 의해 그룹화

관련 문제