Working with arrays of lists pattern in java
I am writing a card game in java where I need to spread cards from a deck into several columns until I have fixed amount of cards left开发者_开发知识库. This is how I do this.
public class Column extends ArrayList {} List deck = Cards.createNewDeck(); Column[] columns = new Column[10]; int c = 0; while (deck.size() > 50) { if (c == 10) { c = 0; } if (columns[c] == null) { columns[c] = new Column(); } columns[c].add(Cards.dealTopCard(deck)); c += 1; }
This somehow seems clunky. Is there a more readable/comprehensive way of doing the same thing?
public class Column extends ArrayList {}
List deck = Cards.createNewDeck();
Column[] columns = new Column[10];
int c = 0;
for (int i = 0; deck.size() > 50; i = (i+1)%10)
{
if (columns[i] == null)
columns[i] = new Column();
columns[i].add(Cards.dealTopCard(deck));
}
The modulo (%
) operator gives the remainder of the integer division between the two numbers effectively giving you a number that goes back to 0 when reaching 10.
By the way you should decide: use a bidimensional array or just ArrayLists
, don't mix things.
Then since generics do exist, use them instead that extending classes: that's what parametric polymorphism is for! Something like:
ArrayList<Int, ArrayList<Card>> columns = new ArrayList<ArrayList<Card>>();
- Don't use raw types.
- Don't mix arrays with lists.
My suggestion is to define List<Pile<Card>> columns
, where Pile<Card>
has a List<Card>
.
Then define a dealer type that converts a Deck<Card>
into multiple Pile<Card>
. That makes it easier to plug in different deck-to-piles strategies just in case.
精彩评论