【问题标题】:Removing String array from ArrayList using an Iterator使用迭代器从 ArrayList 中删除字符串数组
【发布时间】:2019-07-26 05:47:43
【问题描述】:

我正在尝试使用IteratorArrayList 中删除给定的String 数组。获取给定应用程序的列表。我正在使用我的课本作为资源,但我很困惑为什么会收到错误cannot find symbol - method iterator();。我应该使用Iterator 从我的ArrayList 中删除给定的String 吗?还是我应该使用更好的循环?

非常感谢。

    public void removeApp(String name)
{
    Iterator<App> it = name.iterator(); 
    while(it.hasNext()) {
        App app = it.next();
        String appName = app.getName();
        if (appName.equals(name)) {
            it.remove();
            System.out.println(appName + "has been removed.");
        }
    }
    System.out.println("Can't find app. Please try again.");
}

【问题讨论】:

  • @AnuragSrivastava 这似乎是一个与这个问题完全不同的问题。

标签: java if-statement arraylist while-loop iterator


【解决方案1】:

这是因为参数name是一个字符串,你只能在实现Iterable的对象上调用.iterator()

name.iterator(); // here is the error

请参阅documentation 了解更多详细信息(和实现)。

【讨论】:

    【解决方案2】:

    我是否应该使用迭代器从我的 数组列表?还是我应该使用更好的循环?

    Iterable(ArrayList 是一种实现)上的 for/foreach 循环并非旨在在迭代期间删除元素。您使用 Iterator 的方法是正确的。

    你可以这样做:

    List<App> list = ...;
    for(Iterator<App> it = list.iterator(); it.hasNext(); ) {
        App app = it.next();
        String appName = app.getName();
        if (appName.equals(name)) {
            it.remove();
            System.out.println(appName + "has been removed.");
        }
    }
    

    或者您也可以使用List.removeIf(),例如:

    List<App> list = ...;
    list.removeIf(app -> app.getName().equals(name));
    

    【讨论】:

      【解决方案3】:

      您在名称参数上调用.iterator(),而不是在应用列表上。

      此外,您应该在删除应用程序后(在it.remove(); System.out.println(appName + "has been removed."); 之后)立即return,否则您将始终打印“找不到应用程序。请重试。” (除非您可以拥有多个同名的 App 对象)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-18
        • 2012-11-30
        • 2016-01-19
        • 2014-01-14
        • 1970-01-01
        • 2012-01-06
        • 1970-01-01
        • 2019-11-03
        相关资源
        最近更新 更多