采用数组的Java构造函数

时间:2012-11-16 18:39:50

标签: java constructor

如何创建一个构造函数来获取卡片并将它们添加到一个arrayList的手中?下面是我的3个构造函数到目前为止......

“该类应提供一个默认构造函数(创建一个空手),一个构造函数,它接受一组卡片并将它们添加到手中,构造函数需要另一只手并将卡片添加到此手”

更新:

  public class Hand {

    private List<Hand> hand = new ArrayList<Hand>();

    public Hand(){
        hand = new ArrayList<Hand>();
    }

    public Hand(Card[] cards){
        //this.hand.addAll(Arrays.asList(cards));
        //this.hand = new ArrayList<Hand>(Arrays.asList(cards));]
    }

    public Hand(Hand cards){
         this.hand = Arrays.asList(cards);
    }   
  }

3 个答案:

答案 0 :(得分:2)

您应该将列表作为Hand类中的实例变量:

public class Hand {
    private List<Card> cards;

    public Hand(Card[] cards) {
        this.cards = Arrays.asList(cards);
    }
}

目前,您正在声明一个局部变量,该变量在构造函数返回后立即超出范围。

<强>更新

Hand类本身中列出Hand是没有意义的。 IMO,最好让每个Player保留自己的Hand

据了解,您希望拥有一个初始化卡列表的构造函数,以及一种将卡添加到该列表的方法。如下:

public class Hand {
    private List<Card> cards;

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

    public void addCards(Card... cards) {
        this.cards.addAll(Arrays.asList(cards));
    }
}

以下是构造函数:

public class Hand {
    private List<Card> cards;

    //constructor to create an empty hand
    public Hand() { 
        this.cards = new ArrayList<Card>();
    }

    //constructor to create an empty hand and add all provided cards to it
    public Hand(Card[] cards) {
        this();
        this.cards.addAll(Arrays.asList(cards));
    }

    //constructor to create an empty hand and add all cards in the provided hand
    public Hand(Hand hand) {
        this();
        this.cards.addAll(hand.getCards());
    }
}

答案 1 :(得分:1)

public Hand(Card[] cards){
    ArrayList<Card> hand = new ArrayList<Card>(Arrays.asList(cards));
}

答案 2 :(得分:0)

使用java.util.Arrays

List<Card> hand = Arrays.asList(cards);