小编Art*_*lay的帖子

Java:迭代 ArrayList 时出现 NoSuchElementException

我想删除重复的元素,因此迭代 ArrayList 并比较两个连续的元素。(人物具有可比性)

ArrayList<Person> persons = getHelper().findAllPersons();
Collections.sort(persons);
ListIterator<Person> it = persons.listIterator();
if(it.hasNext()) {
    Person tmp = it.next();
    while(it.hasNext()) {
        if(tmp.getLastDiscovered() == it.next().getLastDiscovered()) {
            getHelper().delete(tmp);
        }
    tmp = it.next();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在以下位置收到 NoSuchElementExceptiontmp = it.next();

难道不应该while(it.hasNext())阻止吗?

java iterator arraylist nosuchelementexception

2
推荐指数
1
解决办法
1783
查看次数