[英]Removing index in an arraylist of arraylists
I am trying to remove an arraylist within a list of arraylists but it does not seem to be working. 我试图删除arraylists列表中的arraylist但它似乎没有工作。 In context of my code, I have multiple routes which are in an arraylist.
在我的代码的上下文中,我有多个路由在arraylist中。 Each route is a arraylist of places.
每条路线都是地方的arraylist。
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. 我也试过routes.remove(i)没有做任何事情。 Edit: By "not working" I mean that nothing is being removed, it still displays routes which should have been removed based on my condition.
编辑:通过“不工作”我的意思是什么都没有删除,它仍然显示应根据我的条件删除的路线。
To remove elements from a Collection
while iterating over it, you should use its Iterator
; 要在迭代过程中从
Collection
删除元素,您应该使用它的Iterator
; otherwise, you'll end up running into a ConcurrentModificationException
(which I expect is what you're referring to by "not working"): 否则,你最终会遇到
ConcurrentModificationException
(我希望你所指的是“不工作”):
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
: 此外,使用Java 8,您可以使用
List#removeIf
:
public static void removeBadRoutes(ArrayList<ArrayList<Place>> routes, Expedition e) {
routes.removeIf(route -> !isGoodRoute(route, e));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.