I have CardType1 and CardType2 that extends Card, and an Area that has an ArrayList of Card. This array will be filled with CardType1 and CardType2 objects, but I need to eventually access them like:
for (CardType1 card : this.cards) { ...
An overview:
public class Area {
List<Card> cards = new ArrayList<Card>();
..
}
public class Card {..}
public class CardType1 extends Card {..}
public class CardType2 extends Card {..}
How can I iterate over only one of the subtypes in my List<Card> cards list?
You cannot do it this way, because the type of object in cards, is
Card, notCardType1:You can however do this:
What I am doing here, is iterating through the cards, as you were (except my type is the most general type to both besides
Object). Then I check if the card is of typeCardType1, orCardType2, using theinstanceOfoperator and cast it to that type, then handle it.