2012-10-29 5 views
0

의 카드를 가지고있는 및 CardType2Card이고, 길이는 Area입니다. 이 배열은 CardType1CardType2 개체 가득합니다,하지만 난 결국처럼 접근 할 필요가 :다양한 유형의 객체가 포함 된 Java ArrayList

for (CardType1 card : this.cards) { ... 

개요 : 나는 하위 유형의 하나에서 반복 수있는 방법

public class Area { 

    List<Card> cards = new ArrayList<Card>(); 
    .. 
} 

public class Card {..} 

public class CardType1 extends Card {..} 

public class CardType2 extends Card {..} 

List<Card> cards 목록에 있습니까?

+2

지금까지 좋은 점은 무엇입니까? – Vlad

+0

어디서 그런 접근이 필요합니까? 이기종 목록을 갖고 있지 않은 것보다 이기종 목록을 갖는 것이 이치에 맞지 않는 경우. –

+1

상자 밖에서 약간 생각한 것처럼, 당신은 추가적으로 피벗 엘리먼트를 저장하는 방식으로 arraylist를 파티션 할 수 있고, CardType1 타입의 엘리먼트와 그 이후의 모든 것을 CardType2의 모든 엘리먼트로 유지할 수 있습니다. 이렇게하면 각 삽입에 arraylist를 정렬하고 업데이트해야하지만 작업이 필요하지는 않지만 요소를 반복하는 시간을 절약 할 수 있습니다. –

답변

3

, 개체의 유형 때문에 카드에, Card 아니다 CardType1 :

for(CardType1 card : this.cards){ ... 

당신은 그러나이 작업을 수행 할 수 있습니다

for(Card card : this.cards) { 
    if (card instanceof CardType1) { 
     CardType1 card1 = (CardType1) card; 
     // do something with the card1 
    } else { 
     CardType2 card2 = (CardType2) card; 
     // do something with the card2 
    } 
} 

내가 여기에서하는 일은 카드를 반복하는 것입니다 (내 유형은 Object 외에도 가장 일반적인 유형을 제외하고). 그런 다음 카드가 CardType1이거나 CardType2인지 확인한 후 instanceOf 연산자를 사용하여 해당 유형으로 캐스팅 한 다음 처리합니다.

+0

시간 내 주셔서 감사합니다. – TMichel

2

Card으로 각 항목을 반복해서 만 볼 수 있습니다. CardType1을 사용하여 반복 할 수 있다면 CardType2 유형의 카드를 만났을 때 오류가 발생합니다. 당신은 당신이 card 여부를 확인해야합니다 원하는 것을 들어

CardType1 또는 CardType2의 인스턴스 다음 적절하게 card 캐스트 : 당신은 그것을 이런 식으로 할 수없는

for (Card card : this.cards) { 
    if (card instanceof CardType1) { 
     CardType1 cardType1 = (CardType1) card; 
     // do something with cardType1 
    } 
    else if (card instanceof CardType2) { 
     CardType2 cardType2 = (CardType2) card; 
     // do something with cardType2 
    } 
} 
0
ArrayList<Card> cards = new ArrayList<>(); 
cards.add(new CardType1()); 
cards.add(new CardType2()); 

for(Card card : this.cards){ 
    // card can be any thing that extends Card. i.e., CardType1, CardType2 
    if(card instanceOf CardType1){ 
     //do cardType1 things 
    } 
    else if(card instanceof CardType2){ 
     // do CardType2 things 
     } 


} 
2

Dominic과 Nathan의 답변은 표시에 있습니다. 당신은 구아바를 사용하는 경우, 당신은 바로 가기로 Iterables.filter(Iterable, Class) 사용할 수 있습니다

for (CardType1 card : Iterables.filter(cards, CardType1.class)) { 
    ... 
} 

를 문서에서 : 클래스 type

반환 모든 인스턴스를 unfiltered에. 리턴 된 반복 가능 요소는 클래스가 type이거나 서브 클래스가 type 인 요소를가집니다.

+0

좋지만이 반복마다이 호출 필터가 있습니까? 내 자바 녹슨입니다. –

+2

+1이고, 전체 반복자에 대해서'filter'를 한 번만 호출합니다. 그러나'filter'_will_는 본질적으로 주어진 반복자의 모든 member_에 대해'instanceof'를 호출합니다. 구아바 충분히 복잡한 프로젝트에 대한 필수입니다 :) – Brian

+0

@ DominicBou-Samra 귀하의 질문을 이해하지 못했습니다 - 전화 대리인 유형에 할당 할 수없는 요소를 건너 뛰는 사용자 정의'Iterator'를 반환하는'Iterators.filter'. [(출처)] (http://docs.guava-libraries.googlecode.com/git/javadoc/src-html/com/google/common/collect/Iterators.html#line.758) –