【发布时间】:2015-12-30 21:40:27
【问题描述】:
//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。 -
是的,你说的很对。我将其命名为仅用于发布,以便读者知道这是发生 .remove() 问题的方法。
标签: java while-loop iterator illegalstateexception