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

Nay*_*ign 7 java iterator foreach-loop-container

基本上,用户提交Iterator在ArrayList中搜索的String.找到时,Iterator将删除包含String的对象.

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

Friend current = it.next();
String currently = current.getFriendCaption();
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

T.J*_*der 38

您不需要在一行上使用它们,只需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
    }
}
Run Code Online (Sandbox Code Playgroud)

完整演示:

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;
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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

After:
non-match
non-match