3

I am trying to remove an arraylist within a list of arraylists but it does not seem to be working. In context of my code, I have multiple routes which are in an arraylist. Each route is a arraylist of places.

public static void removeBadRoutes(ArrayList<ArrayList<Place>> routes, Expedition e) { 
    for(int i = 0; i < routes.size(); i++) {
        if(!isGoodRoute(routes.get(i), e)) {
            routes.remove(routes.get(i));
        }
    }
}

I also tried routes.remove(i) which didnt do anything. Edit: By "not working" I mean that nothing is being removed, it still displays routes which should have been removed based on my condition.

Jytrex
  • 35
  • 5
  • 1
    "Not working" is not going to cut it. ArrayList is a list and, like array, every element will *always* have an index and you can't simply "remove the index". Please tell us how you want it to work in more details. If you want to remove item but keep index unchanged (which you can do by replacing the item with `null`), you can try a reverse loop instead (go from size-1 to 0, then you can keep remove). – Sheepy Apr 30 '18 at 02:32
  • 1
    Possible duplicate of [Calling remove in foreach loop in Java](https://stackoverflow.com/questions/1196586/calling-remove-in-foreach-loop-in-java) – Joe Coder Apr 30 '18 at 02:37
  • Using iterator is a recommended way but you can also clone an original list to remove it's item – royalghost Apr 30 '18 at 02:45

1 Answers1

2

To remove elements from a Collection while iterating over it, you should use its Iterator; otherwise, you'll end up running into a ConcurrentModificationException (which I expect is what you're referring to by "not working"):

public static void removeBadRoutes(ArrayList<ArrayList<Place>> routes, Expedition e) { 
    for (Iterator<ArrayList<Place>> it = routes.iterator(); it.hasNext();) {
        if (!isGoodRoute(it.next(), e)) {
            it.remove();
        }
    }
}

Also, with Java 8, you can use List#removeIf:

public static void removeBadRoutes(ArrayList<ArrayList<Place>> routes, Expedition e) {
    routes.removeIf(route -> !isGoodRoute(route, e));
}
Jacob G.
  • 28,856
  • 5
  • 62
  • 116