简体   繁体   中英

ArrayList of ArrayLists in Java - shortening code

I've made ArrayList ("List of Hands") of ArrayLists ("Hands"), but in not very elegant way. I'm expecting 1-4 Hands and I came up with this idea:

ArrayList<ArrayList<Card>> hands=new ArrayList<ArrayList<Card>>();
i=0;
if(i<playersQuantity){
    ArrayList<Card> hand0=new ArrayList<Card>();
    hands.add(hand0);
    i++;
}
if(i<playersQuantity){
    ArrayList<Card> hand1=new ArrayList<Card>();
    hands.add(hand1);
    i++;
}
if(i<playersQuantity){
    ArrayList<Card> hand2=new ArrayList<Card>();
    hands.add(hand2);
    i++;
}
if(i<playersQuantity){
    ArrayList<Card> hand3=new ArrayList<Card>();
    hands.add(hand3);
}

Do you have any idea how to shorten this code? If I had to expect 20, 100 or more hands, this way would be quite problematic...

How about using a loop, something like this:

for (int i = 0; i < playersQuantity; i++) {
    ArrayList<Card> hand = new ArrayList<Card>();
    hands.add(hand);
}

I would suggest refining your object model a bit by creating a Hand abstraction:

public class Hand {
       List<Card> cards= new ArrayList<>();

       public Hand(List<Card> cards) {
           this.cards = cards;
       }

       public List<Card> getCards() {
           return cards;
       }

       public void setCards(List<Card> cards) {
           this.cards = cards;
       }
}

Note it isn't a good idea to expose a mutable object like this ArrayList in a getter, but let's put that issue aside for now.

Then do this:

ArrayList<Hand> hands = new ArrayList<>();
for(int i = 0 ; i < playersQuantity ; i++) {
    hands.add(new Hand(new ArrayList<Card>()));

}

Or whatever else you need to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM