【问题标题】:ArrayList : remove method throw java.lang.IndexOutOfBoundExceptionArrayList:删除方法抛出 java.lang.IndexOutOfBoundException
【发布时间】:2015-03-03 16:36:52
【问题描述】:

我目前正在通过 AP CS 十一人实验室工作,该实验室让您开发自己的纸牌和套牌类来模拟纸牌游戏。我目前正在编写一个 shuffle 方法,该方法接受一个 Deck 对象并随机打乱其中的 Card 对象。到目前为止,这是我的方法:

public void shuffle() {
 ArrayList<Card>copy = new ArrayList <Card> ();
 for (int i = cards.size(); i >= 0; i--) {
   int d = (int)(Math.random()*i);
   copy.add(cards.get(d));
   cards.remove(d);
 }
size = cards.size();
cards = copy;
}

cards 是一个用多个Card 对象初始化的ArrayList。此代码工作正常,但前提是 cards.remove(d); 行不存在。为什么是这样?我该如何解决?

如果这有帮助,这里是为您提供的 Deck 的构造函数类:

public Deck(String[] ranks, String[] suits, int[] values) {
    cards = new ArrayList<Card>();
    for (int j = 0; j < ranks.length; j++) {
        for (String suitString : suits) {
            cards.add(new Card(ranks[j], suitString, values[j]));
        }
    }
    size = cards.size();
    shuffle();
}

【问题讨论】:

  • 当有问题的行出现时会出现什么问题?
  • 程序可以编译,但一旦运行,我就会收到java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 错误。
  • 如果那一行不存在,它运行良好

标签: java methods arraylist


【解决方案1】:

看看你的代码

for (int i = cards.size(); i >= 0; i--) {

这将在 size 为 0 时进入循环(当没有剩余卡片时),因此 java.lang.IndexOutOfBoundsException

将循环条件中的 &gt;= 0 更改为 &gt; 0

for (int i = cards.size(); i > 0; i--) {

请注意,Collections 已经有一个shuffle 方法,它以List 为参数。

【讨论】:

    【解决方案2】:

    您尝试在没有剩余卡片时移除卡片(即当cards.size() == 0 时)。通过将循环终止条件更改为i &gt; 0 来修复它。

    或者,我可能会以不同的方式编写循环:

    while (!cards.isEmpty()) {
        int d = (int) (Math.random() * cards.size());
        copy.add(cards.remove(d));
    }
    

    这对我来说似乎更清楚了。

    【讨论】:

    • 请注意,还有java.util.Collections.shuffle(),它将完成这项工作。我仅将其作为评论提及,因为我认为自己实施 shuffle 是练习的一部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-04
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多