java - 使用一个迭代器删除多个列表的条目

标签 java iterator listiterator

我有 2 个 int 列表 AB 和 1 个 String 列表 C>。它们的长度相同。我想查看 C 并删除除 A 和 B 的条目之外的所有 字符串,并具有相同的索引。例如:

A:[1, 2, 3]                             A:[1, 3]

B:[4, 5, 6]        should turn into     B:[4, 6]

C:["C", "", B"]                         C:["C", "B"]

我当前的代码如下所示:

int i = 0;
for (Iterator<String> iterator = C.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
        A.remove(i);
        B.remove(i);
    }
    i++;
}

但这行不通。

最佳答案

当您按索引删除元素时,以下所有元素的索引都会递减,因此您必须为此调整代码:

int i = 0;
for (Iterator<String> iterator = C.iterator(); iterator.hasNext();) {
    String string = iterator.next();
    if (string.isEmpty()) {
        // Remove the current element from the iterator and the list.
        iterator.remove();
        A.remove(i);
        B.remove(i);
        // don't increment i in this case, since the former i+1'th element
        // of A and B just became the new i'th element
    } else {
        i++;
    }
}

关于java - 使用一个迭代器删除多个列表的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766471/

相关文章:

java - 在 HashMap Java 上迭代两次

c# - IDisposable 项目的迭代器函数

java - 非法转义字符netbeans

java - 包含相同包或不同包的类的文件夹

java - 使用 RowFilter 删除 JTable 中的一行

c++ - 为什么所有列表都被填充

python - 在逗号分隔的文本文件中查找字符,并返回它所属的字符串

Java:在循环中修改列表时避免使用 ListIterator 并发修改异常

java - ListIterator 的 previous() 方法

java - 将 Hibernate 与 OSGi 和 Maven 结合使用