【问题标题】:Java: Keep getting an IndexOutOfBoundsException, can't figure out where I'm using an invalid indexJava:不断收到 IndexOutOfBoundsException,无法弄清楚我在哪里使用了无效索引
【发布时间】:2017-10-02 08:06:29
【问题描述】:

抱歉,如果这是重复的,但我查看了很多答案,但似乎没有一个适用(例如,我的 for 循环从 0 开始,而不是一个常见的错误)。这是字谜文字游戏中使用的一种方法。请帮助我,我已经连续五个小时了,我想我是因为睡眠不足而产生了幻觉。

编辑:错误发生在ugh.remove(thing.charAt(i));这一行

public boolean anagramOfLetterSubset(String thing, ArrayList<Character> reference) {
    ArrayList<Character> ugh = new ArrayList<Character>();
    for (int h = 0; h < reference.size(); h++) {
        ugh.add(reference.get(h));
    }

    for (int i = 0; i < thing.length(); i++) { //cycles through the letters in the word
        for (int f = 0; f < reference.size(); f++) { //cycles through the characters in the reference arraylist
            if ((reference.get(f) == thing.charAt(i)) && (reference.indexOf(thing.charAt(i)) != -1)) { //sees if the letter and the character match
                ugh.remove(thing.charAt(i)); //removes first instance of character
            }
        }
    }
    if (ugh == reference)
        return false;  // change the value returned
    else
        return true;
}

【问题讨论】:

  • 请添加堆栈跟踪。
  • 请注意,ugh == reference 永远不会为真,因为它们是不同的对象实例。
  • thing.charAt(i); 可以返回比ugh 中的元素数更大的索引
  • 我相信remove(thing.charAt(i)) 会调用remove(int) 而不是remove(Object)。请改用remove((Character) thing.charAt(i))
  • 正如@khelwood 所指出的,这将扩大到int

标签: java arraylist indexoutofboundsexception


【解决方案1】:

List 有两个remove 方法:remove(int),用于删除给定索引处的元素;和 remove(Object) 从列表中查找并删除给定对象。

如果您调用remove(thing.charAt(i)),则参数是charchar 不是一个对象,但它可以扩展为一个整数,因此被调用的是 remove(int)。该字符将被用来表示您列表中的索引(因此例外)。

要改为拨打remove(Object),请尝试

ugh.remove((Character) thing.charAt(i));

【讨论】:

    猜你喜欢
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 2018-12-03
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多