gpt4 book ai didi

java - 对象的数组列表只是创建对同一对象java的引用

转载 作者:行者123 更新时间:2023-12-02 04:10:35 25 4
gpt4 key购买 nike

我正在做学校的作业。我正在制作一副简化的牌,你可以选择有多少花色以及每花色有多少张牌。 (花色和等级)。我有一个创建单张卡片的 Card 类和一个创建一副卡片(一副卡片对象)的 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

最佳答案

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.
}

关于java - 对象的数组列表只是创建对同一对象java的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56690056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com