【发布时间】:2013-05-05 06:57:06
【问题描述】:
我想删除重复的元素,因此遍历 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();
}
}
我在tmp = it.next(); 收到 NoSuchElementException
while(it.hasNext()) 不应该阻止这种情况吗?
【问题讨论】:
-
final Set<Person> unqiuePeople = new TreeSet<Person>(persons)将在一行中完成您想要的操作。 -
使用适当定义的比较器/equals() 方法
-
@BrianAgnew 鉴于 OP 已经在使用
Collections.sort来订购我认为已经定义的项目。
标签: java arraylist iterator nosuchelementexception