简体   繁体   中英

Removing String array from ArrayList using an Iterator

I'm trying to remove a given String array from an ArrayList using an Iterator . for a list of given apps. I'm using my class book as a resource for this, but I'm confused as to why I'm getting the error cannot find symbol - method iterator(); . Should I be using an Iterator to remove a given String from my ArrayList ? Or is there a better loop I should be using?

Thanks very much in advance.

    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.");
}

It's because the parameter name is a string and you can call .iterator() only on objects, that implement Iterable :

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

Please, refer to documentation for more details (and implementations).

You're calling .iterator() on your name parameter, instead of on a List of Apps.

Also, you should return just after you delete the App (after it.remove(); System.out.println(appName + "has been removed."); ) otherwise you will always print "Can't find app. Please try again." (unless you can have various App objects with same names).

Should I be using an Iterator to remove a given String from my ArrayList? Or is there a better loop I should be using?

for/foreach loop on Iterable (which ArrayList is an implementation) are not designed to remove elements during iteration. Your approach with Iterator is the correct one.

You can do in this way :

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.");
    }
}

Or as alternative you can use List.removeIf() such as :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM