简体   繁体   English

从ArrayList中删除两个受索引影响的元素

[英]Removing two elements from ArrayList affected by index

I have 5 points from which I need to remove two for a total of three points. 我有5分,我需要从中删除2分,共3分。 I need to remove two points of all possible combinations from 1-5. 我需要从1-5中删除所有可能组合的两个点。 For example: 0,0 - 0,1 - 0,2 ... 5,1 5,2.. to the end. 例如: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++;
            }

Here is what I had. 这就是我所拥有的。 The problem is, when I remove the first point, the index of the next point changes so I having a hard time keeping track of that. 问题是,当我删除第一个点时,下一个点的索引会发生变化,因此我很难跟踪它。

I thought to use a double for loop like this: 我以为使用double 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++;
            }

But still, I get the following: 但是,我得到以下信息:

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

As you can see, there is a problem with printing out "5" in both columns because the index shifts when I make the first removal. 如您所见,在两列中都打印出“ 5”是有问题的,因为在我第一次删除时索引会移动。 Can anyone provide any suggestions? 谁能提供任何建议?

To accomplish it use your previously created newList as reference and delete elements for testList that you have created. 为此,请使用先前创建的newList 作为参考,并删除已创建的testList元素。

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

This way newList will be unchanged and will have all elements (ie Point ) and testList will have elements after removing that elements. 这样, newList将保持不变,并将具有所有元素(即Point ),而testList将在删除元素后具有元素。

Make a filtered copy via standart library (eg guava collections ) or by manual copying: 通过标准库(例如番石榴收藏 )或手动复制来制作过滤后的副本:

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM