【问题标题】:Java, Using Iterator to search an ArrayList and delete matching objectsJava,使用迭代器搜索 ArrayList 并删除匹配的对象
【发布时间】:2011-12-31 18:38:44
【问题描述】:

基本上,用户提交一个字符串,迭代器在 ArrayList 中搜索该字符串。找到后,迭代器将删除包含该字符串的对象。

因为这些对象中的每一个都包含两个字符串,所以我很难将这些行写成一个。

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

感谢您的帮助!

【问题讨论】:

  • 恐怕这个问题没有多大意义。为什么需要将这些行写成一个?
  • 这对我有帮助,谢谢.. ^^

标签: java iterator foreach-loop-container


【解决方案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
前:
匹配
不匹配
匹配
不匹配
匹配

后:
不匹配
不匹配

【讨论】:

  • 我明白你的回答,非常感谢,问题是当我输入if(it.next().contains(text)) {时它不起作用?我只需要在 ArrayList 中搜索每个对象的某个部分(字符串标题)。
  • @Nayrdesign:确保您正确地声明了Iterator,并且您正在正确处理它返回的内容。例如,您在if (it.next().contains(text)) { 中的示例就像Iterator 正在迭代字符串,但您的问题使它看起来像ArrayList 包含Friend 对象,而不是字符串。完整的演示展示了如何正确地做到这一点。关键位声明Iterator&lt;Friend&gt;,因此Iterator 正在迭代Friend 实例,因此it.next() 将成为Friend,然后您可以执行if (it.next().getFriendCaption().contains(text)) {
  • @TJCrowder 我完全按照你的程序建模了我的程序,但我得到: java.util.AbstractList$Itr.next(AbstractList.java:350) 线程“main”java.util.NoSuchElementException 中的异常) 在 RandomInt.messAroundWithListAgain(RandomInt.java:74) 在 RandomInt.main(RandomInt.java:85)
  • @dyoverdx:我不知道该告诉你什么,显然它不像上面那样完全建模,因为上面的作品。也许问一个问题,引用一个完整但小而独立的示例来说明您遇到的问题,人们将能够帮助您。
猜你喜欢
  • 2012-11-30
  • 1970-01-01
  • 2014-07-12
  • 1970-01-01
  • 2020-06-22
  • 2018-05-26
  • 2014-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多