【问题标题】:How to secure the old position of a list within a list for replacing it by a new one如何在列表中保护列表的旧位置以将其替换为新位置
【发布时间】:2015-11-18 12:48:09
【问题描述】:

我有一个带有点的列表列表(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 循环中。所以我不想遍历新添加的列表。

有什么想法吗?提前致谢

【问题讨论】:

  • 我觉得这个问题应该更清楚。你想达到什么目的?
  • 我试图在遍历所有列表时将一个点插入列表之一。任务是在迭代仍在进行时不要再次查看此查看列表。旧列表需要在旧的位置被新的替换,包含所有旧点+新点
  • @Jürgen,如果列表是可变的,您可以将新的Point 作为list.add(newPoint) 添加到现有列表中,而不是将所有元素复制到新列表中。
  • 我怎么知道它是否可变?
  • @Jürgen,看起来您正在将 listOfList 创建为 new ArrayList&lt;&gt; 并填充到您的程序中。因此,它是可变的,您可以简单地将新点添加到列表中,而无需创建新列表。我正在相应地更新我的答案。

标签: java list for-loop iterator position


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    去掉后就可以使用了

    List.add(int index, E element)
    

    在想要的索引处添加元素

    【讨论】:

      【解决方案3】:

      编辑:基于 OP 的最新 cmets,或者可以将新的 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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-09-14
        • 1970-01-01
        • 2016-01-06
        • 2018-05-06
        • 1970-01-01
        • 2018-04-10
        • 1970-01-01
        • 2018-11-01
        • 1970-01-01
        相关资源
        最近更新 更多