Reputation: 2893
I am trying to remove a "thing" from an arraylist in one class, and add it to another arraylist in a different class.
I have a Player class that holds two array lists, which are of type Creature and type SpecialIncomeCounter. I also have a Bag class that holds an array list of "Things", which are Creatures and SpecialIncomeCounters.
My Creature and SpecialIncomeCounter classes both inherit from my abstract class Thing.
In a third class, I am trying to take "Things" from my Bag array list and add it into the correct array list in my player class.
This is what I am doing now:
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);
}
}
The issue is I can't figure out how to tell if thing is of type SpecialIncomeCounter or Creature.
Any suggestions?
Upvotes: 0
Views: 32
Reputation: 1926
instanceof
is what you're looking for.
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);
}
}
Upvotes: 2