Java,使用Iterator搜索ArrayList并删除匹配的对象

基本上,用户提交一个字符串,Iterator在其中搜索ArrayList。 找到时,Iterator将删除包含String的对象。

因为这些对象中的每一个都包含两个字符串,所以我发现将这些行写成一个字符时很麻

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

谢谢你的帮助!

您不需要在一行上使用它们,只需使用remove删除项目匹配时:

 Iterator 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 list = new ArrayList(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 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 
之前:
比赛
不匹配
比赛
不匹配
比赛

后:
不匹配
不匹配 
Interesting Posts