7

基本的に、ユーザーはイテレータが ArrayList を検索する文字列を送信します。見つかった場合、Iterator は文字列を含むオブジェクトを削除します。

これらのオブジェクトにはそれぞれ 2 つの文字列が含まれているため、これらの行を 1 つとして記述するのに問題があります。

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

助けてくれてありがとう!

4

1 に答える 1

38

1行でそれらを必要とせず、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
前:
マッチ
不一致
マッチ
不一致
マッチ

後:
不一致
不一致
于 2011-11-17T22:03:14.877 に答える