【问题标题】:Removing two elements from ArrayList affected by index从受索引影响的 ArrayList 中删除两个元素
【发布时间】:2014-10-04 23:33:59
【问题描述】:

我有 5 个点,我需要从中删除 2 个点,总共 3 个点。我需要从 1-5 中删除所有可能组合中的两点。例如:0,0 - 0,1 - 0,2 ... 5,1 5,2.. 到最后。

for (int i = 0; i < newList.size()-1; i++){

            count = 0;
            ArrayList<Point> testList = new ArrayList<Point>(newList);

            while (count < K-1){
                testList.remove(i+1);
                count++;
            }

这就是我所拥有的。问题是,当我删除第一个点时,下一个点的索引会发生变化,所以我很难跟踪它。

我想像这样使用双 for 循环:

for (int i = 0; i < newList.size(); i++){
        for (int j = 0; j < newList.size()-1; j++){

            count = 0;
            ArrayList<Point> testList = new ArrayList<Point>(newList);

            while (count < K-1){
                testList.remove(i);
                testList.remove(j);
                count++;
            }

但是,我仍然得到以下信息:

REMOVED: 0, 0
REMOVED: 0, 1
REMOVED: 0, 2
REMOVED: 0, 3
REMOVED: 1, 0
REMOVED: 1, 1
REMOVED: 1, 2
REMOVED: 1, 3
REMOVED: 2, 0
REMOVED: 2, 1
REMOVED: 2, 2
REMOVED: 2, 3
REMOVED: 3, 0
REMOVED: 3, 1
REMOVED: 3, 2
REMOVED: 3, 3
REMOVED: 4, 0
REMOVED: 4, 1
REMOVED: 4, 2
REMOVED: 4, 3

如您所见,在两列中都打印出“5”存在问题,因为在我第一次删除时索引会发生变化。谁能给点建议?

【问题讨论】:

    标签: java for-loop arraylist indexing


    【解决方案1】:

    要完成它,请使用您之前创建的newList 作为参考并删除您创建的testList 的元素。

    while (count < K-1){
        testList.remove(newList.get(i+1));
        count++;
    }
    

    这样newList 将保持不变,并将包含所有元素(即Point),而testList 将在删除这些元素后包含元素。

    【讨论】:

      【解决方案2】:

      通过标准库(例如guava collections)或手动复制制作过滤副本:

      List<Point> original = ...
      List<Point> cleared = new ArrayList<Point>(original.size());
      Set<Integer> dropIndex = new TreeSet<Integer>(Arrays.asList(2, 5, 128));
      
      for (int i = 0, size = original.size(); i < size; i++)
          if (!dropIndex.contains(i))
              cleared.add(original.get(i));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-10
        • 2011-06-24
        • 1970-01-01
        • 2016-07-06
        • 1970-01-01
        • 2013-02-24
        相关资源
        最近更新 更多