2011-11-17 56 views
6

基本上,用戶提交一個迭代器搜索ArrayList的字符串。當發現迭代器將刪除包含該字符串的對象。Java,使用迭代器搜索ArrayList並刪除匹配的對象

因爲這些對象中的每一個都包含兩個字符串,所以我很難將這些行寫成一行。

Friend current = it.next(); 
String currently = current.getFriendCaption(); 

感謝您的幫助!

+3

恐怕這個問題沒有多大意義。爲什麼你需要將這些行寫成一行? –

+1

這是幫助我,謝謝.. ^^ –

回答

34

你不需要他們在同一行,只需使用remove當它匹配刪除項目:

Iterator<Friend> it = list.iterator(); 
while (it.hasNext()) { 
    if (it.next().getFriendCaption().equals(targetCaption)) { 
     it.remove(); 
     // If you know it's unique, you could `break;` here 
    } 
} 

完整的示例:

import java.util.*; 

public class ListExample { 
    public static final void main(String[] args) { 
     List<Friend> list = new ArrayList<Friend>(5); 
     String   targetCaption = "match"; 

     list.add(new Friend("match")); 
     list.add(new Friend("non-match")); 
     list.add(new Friend("match")); 
     list.add(new Friend("non-match")); 
     list.add(new Friend("match")); 

     System.out.println("Before:"); 
     for (Friend f : list) { 
      System.out.println(f.getFriendCaption()); 
     } 

     Iterator<Friend> it = list.iterator(); 
     while (it.hasNext()) { 
      if (it.next().getFriendCaption().equals(targetCaption)) { 
       it.remove(); 
       // If you know it's unique, you could `break;` here 
      } 
     } 

     System.out.println(); 
     System.out.println("After:"); 
     for (Friend f : list) { 
      System.out.println(f.getFriendCaption()); 
     } 

     System.exit(0); 
    } 

    private static class Friend { 
     private String friendCaption; 

     public Friend(String fc) { 
      this.friendCaption = fc; 
     } 

     public String getFriendCaption() { 
      return this.friendCaption; 
     } 

    } 
} 

輸出:

$ java ListExample 
Before: 
match 
non-match 
match 
non-match 
match 

After: 
non-match 
non-match
+0

我明白你的答案,非常感謝,問題是,當我鍵入 'if(it.next()。contains(text)){' 它doesn'工作? 我只需要搜索ArrayList中每個對象的某個部分(String標題)。 – Nayrdesign

+0

@Nayrdesign:確保你正確地聲明瞭'Iterator',並且正在處理它正確返回的內容。例如,你的例子中if(it.next()。contains(text)){'就像迭代器一樣遍歷字符串,但是你的問題看起來像'ArrayList'包含'Friend'對象,而不是字符串。完整的演示顯示如何正確執行此操作。關鍵點是聲明'迭代器',所以'迭代器'迭代'Friend'實例,所以'it.next()'將成爲'Friend',那麼你可以做'if(it.next()。 getFriendCaption()。contains(text)){'。 –

+0

@TJCrowder我模仿我的程序完全在你的後面,但我得到:線程「主」異常java.util.NoSuchElementException \t at java.util.AbstractList $ Itr.next(AbstractList.java:350) \t at RandomInt .messAroundWithListAgain(RandomInt.java:74) \t at RandomInt.main(RandomInt.java:85) – hologram