如何保护列表中列表的旧位置以将其替换为新位置

How to secure the old position of a list within a list for replacing it by a new one

我有一个带点的列表列表(AWT)

List<List<Point>> listOfList = new ArrayList<List<Point>>();

现在我正在迭代它:

for (List<Point> list : listOfList) {
//...
//here i'm looking for a specific Point, if its inside, i add additional point 
//into the new listTemp
List<Point> tempList = new ArrayList<Point>();

我通过将所有点复制到一个新列表中来做到这一点tempList”。 最后我用新的替换旧的列表。

listOfList.remove(list); 
listOfList.add(listTemp); 
}

现在我的问题是如何确保 listTemp 准确地占据 listOfList 中已删除列表的旧位置?所有这些都发生在 for 循环中。所以我不想遍历新添加的列表。

有什么想法吗?提前致谢

去掉后可以使用

List.add(int index, E element)

在想要的索引处添加元素

编辑: 根据 OP 的最新评论,或者可以将新的 Point 添加到找到的特定列表中,而不是创建新列表并替换找到的列表.

for (List<Point> list : listOfList) {
    if (list.contains(specificPoint) {
        //add new point to the same list. 
        list.add(newPoint);
    }
}

在遍历 listOfList 时保留 List 的索引。因此,您需要使用旧式 for 循环:

for (int i = 0; i < listOfList.size(); i++) {
    List<Point> list = listOfList.get(i);

    // ...
    // here i'm looking for a specific Point, if its inside, i add additional point
    // into the new listTemp
    if (list.contains(specificPoint)) {
        List<Point> tempList = new ArrayList<Point>();
        // populate tempList here.
        // ...
        // remove old list from the listOfList
        listOfList.remove(i);
        // insert new list to the same index.
        listOfList.add(i, tempList);
        break;
    }
}

使用 ListIterator 遍历 listOfLists 并使用 ListIterator.set() 将列表替换为新列表:

ListIterator<List<Point>> it = listOfList.listIterator();
while (it.hasNext()) {
    List<Point> list = it.next();
    ...
    it.set(listTemp);
}