我有 2 个 int
列表 A、B 和 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/