2014-01-31 5 views
0

한 클래스의 arraylist에서 "물건"을 제거하고 다른 클래스의 다른 arraylist에 추가하려고합니다.오브젝트 비교 문제

플레이어 클래스에는 Creature 유형 및 SpecialIncomeCounter 유형의 두 배열 목록이 있습니다. Creatures 및 SpecialIncomeCounters 인 "Things"의 배열 목록을 보유하는 Bag 클래스도 있습니다.

My Creature 및 SpecialIncomeCounter 클래스는 모두 내 추상 클래스에서 상속합니다.

세 번째 클래스에서는 Bag 배열 목록에서 "Things"를 가져와 플레이어 클래스의 올바른 배열 목록에 추가하려고합니다.

이것은 내가 지금 뭐하는 거지입니다 :

Thing thing; 
for(int i=0;i<10;i++){ 
    thing = bag.bag.get(i); 
    if(thing == Creature){ //this doesn't work 
     p1.addCreature((Creature)thing); 
     bag.bag.remove(i); 
    } 
    else if(thing == SpecialIncomeCounter){ //this doesn't work 
     p1.addSpecialIncomeCounter((SpecialIncomeCounter)thing); 
     bag.bag.remove(i); 
    } 
} 

문제는 내가 가지 유형의 SpecialIncomeCounter 또는 생물의 경우 확인하는 방법을 알아낼 수 없습니다입니다.

제안 사항?

답변

2

instanceof 당신이 찾고있는 것입니다.

Thing thing; 
    for(int i=0;i<10;i++){ 
     thing = bag.bag.get(i); 
     if(thing instanceof Creature){ 
      p1.addCreature((Creature)thing); 
      bag.bag.remove(i); 
     } 
     else if(thing instanceof SpecialIncomeCounter){ 
      p1.addSpecialIncomeCounter((SpecialIncomeCounter)thing); 
      bag.bag.remove(i); 
     } 
    } 
+0

감사합니다. 나는 instanceof에 대해 완전히 잊었다! – Sarah