被覆盖的对象ArrayList的元素 - Android

时间:2015-12-12 01:27:55

标签: android

我正在尝试初始化一副牌,将它们洗牌,然后将它们放入堆叠中。

在我初始化它们和我洗牌之间的某个时刻,我的数据会被覆盖。

这是我的功能代码:

public void shuffleDeck()
{

    ArrayList<Card> temp = new ArrayList<>();
    Card init = new Card();
    int counter = 0;
    // Initialize the deck
    Log.d("Shuffling Deck", "Starting now");
    for(int i=1;i<14;i++)
    {
        for(int j=1;j<5;j++)
        {
            init.setValue(i);
            init.setSuit(j);
            //Log.d("Value", Integer.toString(i));
            //Log.d("Suit", Integer.toString(j));
            temp.add(init);
            Log.d("Deck Build", "Suit: " + Integer.toString(temp.get(counter).getSuit()) + " ,Value: " + Integer.toString((temp.get(counter).getValue())));
            counter++;
        }
    }



    Card a = new Card();
    int index;
    Random rnd = ThreadLocalRandom.current();
    for(int l=temp.size()-1; l>0; l--)
    {

        index = rnd.nextInt(l+1);
        //Log.d("Deck Pre-Shuffle", "Suit: " + Integer.toString(temp.get(l).getSuit()) + " ,Value: " + Integer.toString((temp.get(l).getValue())));
        a = temp.get(index);
        temp.set(index,temp.get(l));
        temp.set(l,a);
        Log.d("Deck Shuffle", "Suit: " + Integer.toString(temp.get(l).getSuit()) + " ,Value: " + Integer.toString((temp.get(l).getValue())));
    }

    // Move deck to a stack
    for(int k=0; k<52; k++)
    {
        Log.d("Deck Push", "Suit: " + Integer.toString(temp.get(k).getSuit()) +" ,Value: " + Integer.toString((temp.get(k).getValue())));
        deck.push(temp.get(k));
    }
}

Card类有两个属性,value和suit,都是int。

当我正在登录“Deck Build”时,它看起来像预期的那样(我为你剪短了):

Deck Build﹕ Suit: 1 ,Value: 1
Deck Build﹕ Suit: 2 ,Value: 1
Deck Build﹕ Suit: 3 ,Value: 1
Deck Build﹕ Suit: 4 ,Value: 1
Deck Build﹕ Suit: 1 ,Value: 2
Deck Build﹕ Suit: 2 ,Value: 2
Deck Build﹕ Suit: 3 ,Value: 2
Deck Build﹕ Suit: 4 ,Value: 2

但是随后洗牌循环中的日志记录如下所示:

Deck Shuffle﹕ Suit: 4 ,Value: 13
Deck Shuffle﹕ Suit: 4 ,Value: 13
Deck Shuffle﹕ Suit: 4 ,Value: 13
Deck Shuffle﹕ Suit: 4 ,Value: 13

有关正在发生的事情的任何想法?

1 个答案:

答案 0 :(得分:2)

在您的代码中

ArrayList<Card> temp = new ArrayList<>();
Card init = new Card();
int counter = 0;
// Initialize the deck
Log.d("Shuffling Deck", "Starting now");
for(int i=1;i<14;i++)
{
    for(int j=1;j<5;j++)
    {
        init.setValue(i);
        init.setSuit(j);
        //Log.d("Value", Integer.toString(i));
        //Log.d("Suit", Integer.toString(j));
        temp.add(init);
        Log.d("Deck Build", "Suit: " + Integer.toString(temp.get(counter).getSuit()) + " ,Value: " + Integer.toString((temp.get(counter).getValue())));
        counter++;
    }
}

仅创建一个 Card对象,因此在for循环中,您只需更改其值/套件并将相同的对象添加到ArrayList。解决方案是在

中创建一个新的Card对象
for(int j=1;j<5;j++) {
    Card init = new Card();
    ...
}