基本上,用户提交一个字符串,迭代器在 ArrayList 中搜索该字符串。找到后,迭代器将删除包含字符串的对象。
因为这些对象中的每一个都包含两个字符串,所以我发现将这些行写成一个很麻烦。
Friend current = it.next();
String currently = current.getFriendCaption();
谢谢你的帮助!
基本上,用户提交一个字符串,迭代器在 ArrayList 中搜索该字符串。找到后,迭代器将删除包含字符串的对象。
因为这些对象中的每一个都包含两个字符串,所以我发现将这些行写成一个很麻烦。
Friend current = it.next();
String currently = current.getFriendCaption();
谢谢你的帮助!
您不需要将它们放在一行中,只需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 列表示例 前: 匹配 不匹配 匹配 不匹配 匹配 后: 不匹配 不匹配