对象数组列表仅创建对相同对象java的引用

时间:2019-06-20 16:12:09

标签: java arraylist

我正在为学校做作业。 我正在制作一副简化的纸牌,您可以选择几套西装,每套西装可以选择几张纸牌。 (西装和排名)。我有一个创建单个卡的Card类和一个创建一副Card(一副Card Objects)的DeckOfCards类。我试图将卡放入ArrayList(在DeckOfCards构造函数内部),但是每次它仅创建对最近创建的卡的引用。我花了几个小时试图找出答案,但在任何搜索中都找不到答案。



public class DeckOfCards
{

    private int counter = 0;
    private ArrayList<Card> cardList = new ArrayList<>();

    public DeckOfCards(int rank, int suit)
    {
        for (int x = 0; x < suit; x++) // x is suit
        {
            for (int y = 0; y < rank; y++)  // y is rank
            {
                cardList.add(counter, new Card(x, y));
                counter++; // counter is position in ArrayList / deck
            }
        }
    }

    public String dealCard(int numOfCards)
    {
        // returns the card (numOfCards)
        return cardList.get(numOfCards).toString();
    }
}

/* Card Class and Constructor
public class Card
{
    private static int SUIT;
    private static int RANK;

    public Card(int suit, int rank)
    {
        this.SUIT = suit;
        this.RANK = rank;
    }

    public String toString()
    {
        return ("S"+ SUIT + "R" + RANK);
    }
}



Depending on the rank and suit the output should be

S1R1
S1R2
S1R3
.
.
.
S4R1
S4R2
S4R3

But the out put is always the last card created
S4R3

2 个答案:

答案 0 :(得分:0)

ArrayList.get(int index)是您的问题。您的dealCard方法正在传递与列表中的索引相同的numOfCards变量(在您的测试案例中,我假设为1、2、3等)。您应该做什么取决于所寻找的行为。

应该洗牌吗? 如果是这样,请看看this

发卡后,是否应将卡从卡组中取出? 如果是这样,您应该使用ArrayList.remove(int index),它既可以将卡片从卡组中取出,又可以同时退回卡片。

除此之外,您的方法应如下所示:

public String dealCard(int numOfCards)
{
    Card[] dealtCards = new Card[numOfCards]; //This could also be another ArrayList if you want, but unless you're going to be adding/removing cards from the returned object afterwards it shouldn't be necessary
    for(int i = 0; i < numOfCards; i++) {
        dealtCards[i] = cardList.get(i); //or cardList.remove(0);
    }
    return dealtCards; //Notice that this will return the same cards each time you call the method if you use cardList.get(i) unless you implement a cyclical counting variable outside of the method and use it inside the method.
}

答案 1 :(得分:0)

如果要在创建卡片时打印卡片,则只需从Card()构造函数中调用toString()方法即可。

...但是,如果您希望从交易卡中打印它们,则需要使用for循环或通过递归调用在arraylist中的每个卡上建立索引(这可能已经在dealCard方法之外进行了)。

我认为您只打印最新卡的原因是因为您的参数-“ numOfCards”是您创建的“实际”卡数-这也是您数组列表中的最后一个索引,可能就是为什么仅打印您最近创建的卡。

PS 我认为您不需要使用计数器来表示数组列表的索引。使用arraylist.add('object')只需将object参数附加到列表的末尾。数组列表中已经存在对象的索引,因此使用计数器排序无法达到目的。

相关问题