有没有更好的方法将对象添加到java中的ArrayList?每当我尝试添加或设置新内容时,它都会将整个数组更改为该对象

时间:2014-01-31 04:17:27

标签: java arraylist

我正在制作纸牌游戏并尝试使用由两个字符串元素组成的Card对象:卡片和套装的价值,以及创建这些卡片对象的ArrayList。我已经尝试使用下面的代码,并注意到每次我添加一个新元素,我看到每个元素都被更改为与最近添加的元素具有相同的数据 这是我的代码:

import java.util.*;
public class testArrayList
{
    public static void main(String args[])
    {
        ArrayList<Card> deck= new ArrayList<Card>();

        String cValues[] = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"};
        int cVLength= cValues.length;
        String cSuit[] = {"Hearts", "Diamonds", "Clubs", "Spades"};
        int cSLength= cSuit.length;
        for(int k=0; k<cVLength; k++)
        {
            for(int j=0; j<cSLength; j++)
            {
                deck.add(new Card(cValues[k],cSuit[j]);
            }
        }
        System.out.println(deck.get(0).getValue()+ " "+ deck.get(0).getSuit());
        System.out.println(deck.get(1).getValue()+ " "+ deck.get(1).getSuit());
        System.out.println(deck.get(50).getValue()+ " "+ deck.get(50).getSuit());
        System.out.println(deck.get(51).getValue()+ " "+ deck.get(51).getSuit());
    }

}
class Card
{
    private static String value;
    private static String suit;
    public Card(String v, String s)
    {
        value   = v;
        suit    = s;
    }
    public static String getValue()
    {
        return value;
    }
    public static String getSuit()
    {
        return suit;
    }
}

请帮助任何非常感谢!

2 个答案:

答案 0 :(得分:2)

你的班级Card有一个致命的缺陷,它只有静态字段。

class Card
{
  private String value; // <-- not static
  private String suit;  // <-- not static
  public Card(String v, String s)
  {
    this.value   = v;   // <-- really not static.
    this.suit    = s;
  }
  public String getValue() // <-- also not static.
  {
    return value;
  }
  public String getSuit()
  {
    return suit;
  }
}

答案 1 :(得分:2)

问题不在于您ArrayList,问题在于您Card类......

private static String value;
private static String suit;

基本上意味着无论您将其设置为什么值,它都会针对Card的每个实例进行更改

删除static声明,例如

class Card {

    private String value;
    private String suit;

    public Card(String v, String s) {
        value = v;
        suit = s;
    }

    public String getValue() {
        return value;
    }

    public String getSuit() {
        return suit;
    }

}

使用您的示例运行它时,它现在输出...

Ace Hearts
Ace Diamonds
King Clubs
King Spades