如何在访问新项目的同时删除旧的 ArrayList 项目

How to remove old ArrayList items while simultaneously accessing new ones

我有一个读取文本文件的程序,将某些对象添加到 ArrayList,然后稍后访问它们以显示对象。但是,该文件非常大(850 万行),因此 ArrayList 也是如此(我认为这是导致我的程序在我 运行 它时立即挂起的原因。)

我想在访问较新的项目时删除 ArrayList 中较旧的项目,这样我可以使 ArrayList 的大小保持较小。它似乎不适用于我当前的代码 - 这是删除 ArrayList 中旧项目的正确方法吗?

相关代码如下:

void drawPoints() {
  for (int i = 0; i < places.size(); i++) {
    places.get(i).placeCoordinate();
    places.get(i).fadeCoordinate();
      if (i >= 1) {
        places.remove(i - 1);
      }
   }
}

一些注意事项:

如果您有想要强制执行的尺寸,比方说 10,那么只要您向 ArrayList 添加内容,就可以简单地进行检查:

ArrayList<Thing> list = new ArrayList<Thing>();

list.add(thing);

if(list.size() == 10){
   list.remove(0); //removes the oldest thing
}

或者如果你真的想在循环 ArrayList 时删除一些东西,你可以简单地向后循环,这样索引的移动就不会干扰循环变量:

  for (int i = places.size()-1; i >= 0; i--) {
    places.get(i).placeCoordinate();
    places.get(i).fadeCoordinate();
      if (i >= 1) {
        places.remove(i - 1);
      }
   }

或者您可以使用 Iterator:

ArrayList<Thing> list = new ArrayList<Thing>();

//create your Iterator
Iterator<Thing> iterator = list.iterator();

//loop over every Thing in the ArrayList
while(iterator.hasNext()){
  Thing thing = iterator.next();

  thing.doSomething();

  if(thing.shouldBeRemoved()){
    //Iterator allows you to remove stuff without messing up your loop
    iterator.remove();
  }
}