Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between ArrayLists in Java

Sorry, I thought this was an inheritance question: it was an ArrayList question all along!

Ok, my problem is more specific than I thought. So I have two families of classes. Cards, and Zones. Zones are boxes for holding card.

The first two subClasses of Zone, ZoneList and ZoneMap are meant to be two different ways of storing Cards. Further subclasses, such as Hand, and PokerHand, have their own specific ways of dealing with the cards they store.

Where it gets complicated is that Card also has subClasses, such as PokerCard, and that the subclasses of ZoneList and ZoneMap are meant to organize those.

So in ZoneList I have protected ArrayList<Card> cardBox; and in PokerHand I expected to be able to declare cardBox = new ArrayList<PokerCard>(); since PokerCard is a Card. The error I am getting is that I apparently can't cast between Card and GangCard when it comes to ArrayLists... So I was trying to fix this by just redeclaring cardBox as private ArrayList<PokerCard> cardBox; inside PokerHand, but that resulted in the hiding that was bugging up my program.

SO really, the question is about casting between ArrayLists? Java tells me I can't, so any ideas on how I can?

z.

like image 709
Ziggy Avatar asked Dec 11 '08 06:12

Ziggy


2 Answers

Marc and kolstae have given good answers in terms of how to get around the problem, but I think it's worth explaining why your original code doesn't work.

To simplify matters, I tend to put the problem in terms of fruit. Suppose we have:

List<Banana> bananaBunch = new ArrayList<Banana>();
List<Fruit> fruitBowl = bananBunch;
fruitBowl.add(new Apple());

If this is allowed, we end up with an apple in a bunch of bananas, which is obviously a bad thing. So, where is the problem? The first line has to be okay, and the third line has to be okay - you can add any kind of fruit to List<Fruit> - so the problem has to be in the second line. That's what's prohibited, precisely to avoid this kind of issue.

Does that help at all?

like image 108
Jon Skeet Avatar answered Oct 04 '22 10:10

Jon Skeet


If I understand you correctly, you should probably declare:

public class ZoneList<T extends Card> {
   protected List<T> cardBox;
}

public class PokerHand extends ZoneList<PokerCard> {
   public PokerHand() {
      cardBox = new ArrayList<PokerCard>();
   }
}
like image 23
refrus Avatar answered Oct 04 '22 08:10

refrus