迭代器在调用 .next() 后抛出非法状态异常


//This method compares two ArrayLists of strings and compares whether the words in one array list contain the letters in the other.
    public static void remove()
    {
        //Create iterators for both stringList and letterList
        Iterator<String> iterWords = stringList.iterator();
        Iterator<String> iterLetters = letterList.iterator();
        //First while loop will go over all strings in stringList via the iterWords iterator
        while(iterWords.hasNext())
        {
            //iterWords now has a .next() call
            String word = iterWords.next();
            //Second while loop that should run over each letter in letterList and compare it to each word in stringList
            while(iterLetters.hasNext())
            {
                //iterLetter now has a .next() call
                String letter = iterLetters.next();
                //if statement to remove the entry in stringList if it does not contain the current letter.  It is this part that throws the illegalstateexception
                if(word.contains(letter) == false)
                {
                    //This is the line that is causing the illegalstateexceptions
                    iterWords.remove();
                }           
            }
        }
    }

大家好,我正在寻找有关我在迭代两个数组列表时遇到的异常的一些见解。 我已经简化了上面的数组列表,并删除了任何与问题无关的方法。我在最后一个 iterWords.remove(( 上收到一个非法状态异常。 在外面的while循环中,我已经完成了iterWords.next((,所以iterWords.remove((应该看到要删除的东西。
我猜这是抛出异常,因为我从内部 while 循环调用 iterWords.remove((。 你认为可能是这样吗?感谢您提供的任何见解。

首先,您应该阅读并发布异常。

第二:你给remove()打电话好几次,在只叫next()一次之后:有多少字母不包含在单词中。

第三:由于您总是使用相同的字母迭代器,因此一旦您完成了第一个单词,您就不再迭代字母了。

因此,您必须:

  • 删除单词后立即停止迭代字母
  • 在外部循环的每次迭代中重新创建字母迭代器。或者更好的是,只需使用 foreach 循环:内部循环不需要迭代器。如果您使用以下方法,您的代码将更简单、可读且更安全:

    for (Iterator<String> it: words; it.hasNext(); ) {
        String word : it.next();
        if (anyLetterNotInWord(letters, word) {
            it.remove();
        }
    }
    

如果您使用的是Java 8,则可以将其简化为">

words.removeIf(word -> anyLetterNotInWord(letters, word));

其中anyLetterNotInWord()可以定义为

return letters.stream().anyMatch(letter -> !word.contains(letter));