【问题标题】:Removing elements from a List is causing for loop not to increment?从列表中删除元素导致for循环不增加?
【发布时间】:2016-08-20 03:57:28
【问题描述】:

如果列表中的元素已包含在文本文件中,我正在尝试删除

例如:如果字符串 "Person123" 在文本文件中,则应从列表中删除字符串 "Person123"

以下是我目前的尝试。但是,我在迭代“MyList”时遇到问题,int 值似乎没有增加,这导致仅删除一个字符串元素,而不是两个。

我该如何解决这个问题?

当前代码:

for (Map.Entry<Person, List<String>> entry : mapOfPeopleAndDescriptions.entrySet()) {
    List<String> textFileValues= readFromTextFile(filePath);
    List<String> myList = entry.getValue();

    for (int i = 0; i < myList.size(); i++) {

                if(textFileValues.contains(myList.get(i)){

                    LOGGER.info("In loop- int: {}",i );
                    myList.remove(myList.get(i));

                }

                LOGGER.info("Out of loop- int: {}",i );

            }

    }

我得到的输出:

In loop- int: 0
Out of loop- int: 0
Out of loop- int: 1
Out of loop- int: 0
Out of loop- int: 1
Out of loop- int: 0

【问题讨论】:

  • 向后迭代列表。另外,请使用myList.remove(i)。或使用Iterator
  • @AndyTurner 你是什么意思?
  • for (int i = myList.size(); i &gt;= 0; i--) {
  • 这是一个错字,现在改了,谢谢
  • myList.removeAll(textFileValues) 会比这个循环容易得多。

标签: java list for-loop dictionary int


【解决方案1】:

for 循环是不必要的。只需使用List.removeAll:

myList.removeAll(textFileValues);

请注意,如果您是通过索引进行迭代并删除元素,则应该反过来:

for (int i = myList.size(); i >= 0; i--) {
  myList.remove(i);
}

否则,您将需要在循环中更改i 的值以避免跳过下一个元素。

【讨论】:

    【解决方案2】:

    您应该使用迭代器,然后调用 remove 方法:Iterator.remove()。

    this thread

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 2017-04-25
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      • 1970-01-01
      相关资源
      最近更新 更多