尝试使用另一个类构造函数初始化java中的arraylist

时间:2017-03-07 19:58:54

标签: java arraylist

所以我试图写一个总类卡并让它给玩家一张卡片或电脑,但我需要"初始化手"我似乎无法弄明白。

// 2 arg const 
public Card(String suit, int rank)
{
    this.suit = suit;
    this.rank = rank;
}

上面是卡类

的2参数构造函数
private String name;
private ArrayList<Card> hand = new ArrayList<Card>();

// computer constructor
public Player()
{
    name = "Computer";
    hand.add(1, null);
}

// actual player constructor
public Player(String name)
{
    this.name = name;
    // This is where the hand initialization goes.
}

2 个答案:

答案 0 :(得分:0)

例如,您想要hand.add(new Card("hearts",10))。为手中的每张卡片做到这一点。

答案 1 :(得分:0)

我认为如果你只是将ArrayList作为参数传递并将实例变量设置为等于它就没问题。因为它是一个指针引用,所以它将引用相同的ArrayList。

另一件事是你可以创建一个新的ArrayList并添加hand参数中的所有卡片,就像forgivenson所说的那样,过去我已经完成了两个并且两者都有效。

另一件事是你可能需要导入卡,如果它不在同一个包中(我可能错了,但如果我是正确的我)。但我认为玩家和卡会进入同一个包裹。