Java, Использование Iterator для поиска в ArrayList и удаления соответствующих объектов - PullRequest
7 голосов
/ 18 ноября 2011

Обычно пользователь отправляет строку, которую итератор ищет в ArrayList.При обнаружении итератор удалит объект, содержащий строку.

Поскольку каждый из этих объектов содержит две строки, я нахожу проблемы с записью этих строк как одной.

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

Спасибо за любую помощь!

1 Ответ

38 голосов
/ 18 ноября 2011

Они не нужны в одной строке, просто используйте 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
...