2013-05-10 77 views
2

我想刪除重複的元素,因此迭代通過ArrayList並比較兩個連續的元素。 (人具有可比性)Java: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(); 
    } 
} 

我得到tmp = it.next();

一個NoSuchElementException不應該while(it.hasNext())阻止?

+0

'決勝盤 unqiuePeople =新TreeSet的(人)'會做你在一行中想要的東西。 – 2013-05-10 14:53:11

+0

使用適當定義的比較器/等於()方法 – 2013-05-10 14:57:00

+0

@BrianAgnew假設OP已經在使用'Collections.sort'來訂購物品,我假定這已經定義。 – 2013-05-10 15:01:20

回答

4

問題是您要撥打it.next()兩次,這會使迭代器前進兩次。

您應該存儲該值以避免重複副作用。

Person person = it.next(); 
    if (tmp.getLastDiscovered() == person.getLastDiscovered()) { 
     getHelper().delete(tmp); 
    } 
    tmp = person; 

或者,你可以使用for-each循環,以避免需要用迭代器(我承擔全部Person不爲null)互動:

Person tmp = null; 
for (Person person : persons) { 
    if (tmp != null && tmp.getLastDiscovered() == person.getLastDiscovered()) { 
     getHelper().delete(tmp); 
    } 
    tmp = person; 
} 
1

你打電話it.next()兩次(可能)爲每個it.hasNext()調用,因此你的錯誤。

如果你想刪除重複項,爲什麼不只是填寫一個TreeSet(提供適當的比較器)你的列表? Set的語義是這樣的,你將有一組獨特的元素。

0
while(it.hasNext()) { 
     if(tmp.getLastDiscovered() == it.next().getLastDiscovered()) { 
      getHelper().delete(tmp); 
     } 

之後,'你'即將到達列表的末尾。然後,當它沒有下一個值時,您正在調用下面的行。

tmp = it.next(); 

這給你一個例外。

0

如果您使用的是JDK 1.5.0或更高版本(最有可能的版本,自2004年發佈以來),您可以使用foreach loop來完全避免迭代器,從而大大簡化代碼。

ArrayList<Person> persons = getHelper().findAllPersons(); 
Collections.sort(persons); 
for (Person person : persons) { 
    if(tmp.getLastDiscovered() == person.getLastDiscovered()) { 
     getHelper().delete(tmp); 
    } 
}