java - Java中的对象数组的混洗: Why does this method work for int but not for my objects?

标签 java arrays random shuffle poker

我知道,我知道 - 这里有数百人询问如何用 Java 洗牌和排列 52 个卡片对象,我认为这很简单。我没有使用过集合(基于堆栈的建议)。我已经尝试过费舍尔-耶茨洗牌,但我发现看起来非常奇怪的行为......任何人都可以帮忙吗?

我的解决方案基于这个答案:Random shuffling of an array

对于数字来说,它非常有效。该类有两个数组,一个包含从 0 到 51 的数字,另一个包含 52 个带有各种实例变量(如花色和数字)的 Card 对象。

此代码完美运行:

public void shuffleNums()
   {
       Random rnd = new Random();
       for (int i = this.numbers.length -1; i > 0; i--)
       {
          int index = rnd.nextInt(i + 1);
          // Simple swap
          int temp = this.numbers[index];
          this.numbers[index] = this.numbers[i];
          this.numbers[i] = temp;

       }
   }

但是当我尝试在一副 52 个 Card 对象上使用相同的方法时,如下所示:

public void shuffleCards()
   {
       Random rnd = new Random();
       for (int i = this.cards.length - 1; i > 0; i--)
       {
          int index = rnd.nextInt(i + 1);
          // Simple swap
          Card temp = this.cards[index];
          this.cards[index] = this.cards[i];
          this.cards[i] = temp;

       }
   }

效果不太好。大多数牌都已成功洗牌,但显然我已经丢掉了一半的牌,因为现在数组有大约 16 个 NULL 值,并且只有大约 36 张随机牌。 NULL 似乎随机分布在整个数组中。

我可以轻松解决这个问题,但我想了解为什么会发生这种情况。谁能帮我弄清楚发生了什么事吗?

编辑: 关于我如何初始化数组 - 我已经检查过该数组实际上列出了 52 个 Card 对象,从梅花 2 到黑桃 A。在执行 shuffle() 之前,数组正确包含 52 个卡片对象。后来它包含了大约 36 个 - 给予或索取。

最佳答案

这可能是您初始化卡的问题。

如果你这样做

int[] cards = new int[52];

int数组内的所有内容都会被设置为0,这意味着你可以对其进行操作

但是如果你这样做

Card[] cards = new Card[52];

这些都设置为空,因此如果您对其中一张卡执行操作,则会出现空指针异常。这可以解释为什么您会得到所有这些空值。

关于java - Java中的对象数组的混洗: Why does this method work for int but not for my objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28003297/

相关文章:

Java Spring 启动 : How to find all rows with multiple Ids like findAllByAge(ArrayList<Long> ageList)?

java - 如何使用 Jersey 发布表单数据?

java - Google map Activity 显示空白屏幕

c - 字符串转换时 strtol 结果不匹配

java - 如何生成每个随机数之间具有特定间隔的随机数

c++ - 给定种子和偏移量生成下一个伪随机值

php - 有没有更好的方法来获取限制为 1 的随机记录

java - 通过 MXBeans 收集

java - 如何在 if 语句和 for 循环之外获取数组

PHP & WordPress : print array content