【发布时间】:2014-07-21 09:49:23
【问题描述】:
- 我只是想以此作为开头,我已经完成了我的研究并在此处和其他网站上找到了许多与此问题相关的文章
- 示例包括:
How to populate an array list in a while loop
Pass by value/reference, what?
Create several new objects within a for-loop in Java
这些帮助我确定了我的问题,但每个线程上并没有太多关于如何绕过它或解决它的内容。我认为这是可能的。 无论如何,简而言之,我正在创建一个使用两个类的纸牌程序,
- 'Card'(代表牌组中的单张牌,&
- 'Deck'(表示 52 个卡片对象的容器,-稍后将包含洗牌、发牌等方法)
使用下面的代码,我正在设置一个 Deck 对象并实例化一个 ArrayList,我使用两层 for 循环填充 Card 对象。如果我在迭代时 Sysout,它会澄清对象正在使用正确的值“创建”,但是在循环结束时,调用 ArrayList 上的 Card toString() 方法会显示 52 个 Ace of Clubs 对象 - 这是最后一个要“创建”的卡。显然,它不是创建 52 个单独的 Card 对象,而是引用同一个 Card 对象 52 次,并且因为上次将变量更改为 Ace of Clubs,所以看起来好像有 52 个。
当我在我的 Deck 构造函数中显式创建一个新的 Card 对象时,我不明白它们是如何成为同一个对象的。对于我需要重构以在我的 Arraylist 中实现 52 个不同对象的任何帮助,每个对象都正确填充了各自的等级/套装。
为了清楚起见,我已将我的程序剥离为仅导致此问题的基本代码
提前干杯。
import java.util.ArrayList;
public class Deck {
ArrayList<Card> mainDeck;
public Deck(){
mainDeck = new ArrayList<>();
for(int x = 1;x<=4;x++){
for(int y = 2;y<=14;y++){
mainDeck.add(new Card(y, x));
}
}
}
public void listCards(){
System.out.println(mainDeck.toString());
}
/** I have also tried the below method, which also fails!
*
* public Deck(){
mainDeck = new ArrayList<>();
for(int x = 1;x<=4;x++){
for(int y = 2;y<=14;y++){
Card card = new Card(y, x);
mainDeck.add(card);
}
}
}
*
*
*/
}
public class Card {
public static int rank;
public static int suit;
public static String rankText;
public static String suitText;
public Card(){
}
public Card(int newRank, int newSuit){
rank = newRank;
suit = newSuit;
switch(newSuit){
case 1:
suitText = "Spades";
break;
case 2:
suitText = "Hearts";
break;
case 3:
suitText = "Diamonds";
break;
case 4:
suitText = "Clubs";
break;
default:
break;
}
switch(newRank){
case 2:
rankText = "Two";
break;
case 3:
rankText = "Three";
break;
case 4:
rankText = "Four";
break;
case 5:
rankText = "Five";
break;
case 6:
rankText = "Six";
break;
case 7:
rankText = "Seven";
break;
case 8:
rankText = "Eight";
break;
case 9:
rankText = "Nine";
break;
case 10:
rankText = "Ten";
break;
case 11:
rankText = "Jack";
break;
case 12:
rankText = "Queen";
break;
case 13:
rankText = "King";
break;
case 14:
rankText = "Ace";
break;
}
}
public static int getRank() {
return rank;
}
public static int getSuit() {
return suit;
}
public static String getRankText() {
return rankText;
}
public static String getSuitText() {
return suitText;
}
@Override
public String toString() {
return "Card: = "+ getRankText() + " of "+ getSuitText() + "\n";
}
}
public class App
{
public static void main( String[] args )
{
Deck thisDeck = new Deck();
thisDeck.listCards();
}
}
【问题讨论】:
标签: java for-loop arraylist reference iteration