【问题标题】:Retrieve an element from the current list at the curent index [duplicate]从当前索引的当前列表中检索元素[重复]
【发布时间】:2021-07-20 12:36:04
【问题描述】:

我有一个我正在处理的项目列表。 我正在寻找初始列表中的特定项目,并希望在遍历列表时从该列表中删除找到的项目。 我正在使用for item : list 遍历列表

有没有办法在不操作两个列表的情况下做到这一点?

【问题讨论】:

标签: java


【解决方案1】:

我希望我能正确回答您的问题,但您可以尝试:

Iterator<T> iter = list.iterator();
while (iter.hasNext()) {
    T t = iter.next();
    if (matchesCondition(t)) {
        iter.remove();
    }
}

但我不得不说我不明白你所说的“两个列表”是什么意思。我的回答可能与您完全无关,但我需要更多信息。

【讨论】:

  • remove 是可选操作...
【解决方案2】:

key 成为您需要检查并从列表中删除的值,比如inputList,它是一个整数列表。

for (int i=0; i<inputList.size(); i++) {
     int currentValue = inputList.get(i);
     if (currentValue == key) {
         inputList.remove(i); // this will remove the value at index i
         break;
     }
}

假设我们有一个列表,inputList = [1,2,3] 并且要删除的键是 key=2, 迭代后,列表中的 2 将被删除,如果我们打印剩余的元素,那么 inputList = [1,3] 将是最终结果,并且 2 将被删除。

【讨论】:

  • 第二行应该是inputList.get(i) 而不是input.get(i)。此外,当列表是 [1,2,2,3] 而我的“关键”仍然是 2 时会发生什么?
  • 由于他没有告诉重复值,我认为只有唯一值存在。
猜你喜欢
  • 2011-02-02
  • 1970-01-01
  • 2023-01-02
  • 2016-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多