[英]Java: NoSuchElementException when iterating through ArrayList
I want to delete duplicate elements and therefore iterate through a ArrayList and compare two consecutive elements. 我想删除重复的元素,因此要遍历ArrayList并比较两个连续的元素。 (Persons are comparable)
(人员可比)
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();
}
}
I get a NoSuchElementException at tmp = it.next();
我在
tmp = it.next();
处收到NoSuchElementException tmp = it.next();
Shouldn't the while(it.hasNext())
prevent that? while(it.hasNext())
是否应该防止这种情况发生?
The problem is you are calling it.next()
twice, which will advance the iterator two times. 问题是您两次调用
it.next()
,这会使迭代器前进两次。
You should store the value to avoid repeating the side-effect. 您应该存储该值,以避免重复出现副作用。
Person person = it.next();
if (tmp.getLastDiscovered() == person.getLastDiscovered()) {
getHelper().delete(tmp);
}
tmp = person;
Alternatively, you could use the for-each loop to avoid needing to interact with the iterators (I assume all Person
are not null): 另外,您可以使用for-each循环来避免需要与迭代器进行交互(我假设所有
Person
都不为空):
Person tmp = null;
for (Person person : persons) {
if (tmp != null && tmp.getLastDiscovered() == person.getLastDiscovered()) {
getHelper().delete(tmp);
}
tmp = person;
}
You're calling it.next()
twice (potentially) for each it.hasNext()
call, hence your error. 你打电话
it.next()
两次(潜在的)每个it.hasNext()
调用,因此你的错误。
If you want to remove duplicates, why not just populate a TreeSet (providing the appropriate Comparator) with your list ? 如果要删除重复项,为什么不使用列表填充TreeSet (提供适当的Comparator)呢? The semantics of a
Set
are such that you'll have a distinct set of elements. Set
的语义使得您将拥有一组独特的元素。
while(it.hasNext()) {
if(tmp.getLastDiscovered() == it.next().getLastDiscovered()) {
getHelper().delete(tmp);
}
After that 'while' you are coming to end of the list. 之后,您将进入列表的结尾。 Then when it hasn't got next value, you are calling the line below.
然后,当它没有下一个值时,您将调用下面的行。
tmp = it.next();
That gives you an exception. 那给你一个例外。
If you're using JDK 1.5.0 or later (which you most likely are, since it was released in 2004), you can use a foreach loop to obviate the iterator altogether, greatly simplifying the code. 如果使用的是JDK 1.5.0或更高版本(自2004年发布以来,很可能是这样),则可以使用foreach循环完全消除迭代器,从而大大简化代码。
ArrayList<Person> persons = getHelper().findAllPersons();
Collections.sort(persons);
for (Person person : persons) {
if(tmp.getLastDiscovered() == person.getLastDiscovered()) {
getHelper().delete(tmp);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.