Java, Using Iterator to search an ArrayList and delete matching objects

前端 未结 1 1884
我寻月下人不归
我寻月下人不归 2020-12-06 07:44

Basically, the user submits a String which the Iterator searches an ArrayList for. When found the Iterator will delete the object containing the String.

Because each

相关标签:
1条回答
  • 2020-12-06 07:44

    You don't need them on one line, just use remove to remove an item when it matches:

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

    Full demo:

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

    Output:

    $ java ListExample 
    Before:
    match
    non-match
    match
    non-match
    match
    
    After:
    non-match
    non-match
    0 讨论(0)
提交回复
热议问题