简体   繁体   English

如何从 ArrayLists 的 ArrayList 中删除 ArrayList?

[英]How can I remove an ArrayList from an ArrayList of ArrayLists?

ArrayList<ArrayList<String>> b = new ArrayList<ArrayList<String>>();

I have an ArrayList like the one above with a bunch of ArrayLists as elements, is there a way to remove one of them by index?我有一个像上面那样的 ArrayList,有一堆 ArrayLists 作为元素,有没有办法通过索引删除其中一个?

I created a for loop to remove one of the ArrayLists and got an error message that says there are incompatible types.我创建了一个for循环来删除其中一个 ArrayList,并收到一条错误消息,指出存在不兼容的类型。

for(int f = 0; f < longDistanceInput.size(); f++){
     ArrayList<ArrayList<String>> newLongDisinput = longDistanceInput.remove(f);
}

Thanks in advance.提前致谢。

I tried to do something like this and got an error message says incompatible types我试图做这样的事情并收到一条错误消息说不兼容的类型

for(int f = 0; f<longDistanceInput.size(); f ++){ ArrayList<ArrayList<String>> newLongDisinput = longDistanceInput.remove(f);}

That's because longDistanceInput.remove(f) returns a ArrayList<String> , not a ArrayList<ArrayList<String>> .那是因为longDistanceInput.remove(f)返回ArrayList<String> ,而不是ArrayList<ArrayList<String>>

Try:尝试:

ArrayList<String> newLongDisinput = longDistanceInput.remove(f);

However: be careful removing things while iterating forwards: you will end up removing only half the items in the list, because you skip over the one immediately after the one you remove.但是:在向前迭代时要小心删除内容:您最终只会删除列表中的一半项目,因为您会在删除的项目之后立即跳过项目。

Either iterate in reverse;要么反向迭代; or just use longDistanceInput.remove(0) instead of remove(f) .或者只使用longDistanceInput.remove(0)而不是remove(f) But note that removing from anything but the large-index end of an ArrayList is rather inefficient: if possible, just don't remove things from the list until after the loop.但请注意,从ArrayList的大索引端以外的任何地方删除效率都相当低:如果可能,不要在循环之后从列表中删除东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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