list for循环中删除元素

Posted 程序猿进化之路

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了list for循环中删除元素相关的知识,希望对你有一定的参考价值。

Iterator.remove() is safe, you can use it like this:

List<String> list = new ArrayList<>();

// This is a clever way to create the iterator and call iterator.hasNext() like
// you would do in a while-loop. It would be the same as doing:
//     Iterator<String> iterator = list.iterator();
//     while (iterator.hasNext()) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
    }
}
Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress

 

以上是关于list for循环中删除元素的主要内容,如果未能解决你的问题,请参考以下文章

list循环删除元素

list循环删除单个元素

list for循环中删除元素

JAVA中循环删除list中元素的方法总结

JAVA中循环删除list中元素的方法总结

JAVA中循环删除list中元素的方法总结