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



我有5个点,我需要从中删除两个,总共三个点。我需要从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 (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"是有问题的,因为当我进行第一次删除时,索引会发生偏移。有人能提供什么建议吗?

要完成此操作,请使用先前创建的newList作为引用,并删除已创建的testList的元素。

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

以这种方式newList将保持不变并且将具有所有元素(即Point),并且testList在移除那些元素之后将具有元素。

通过标准库(例如番石榴收藏)或手动复制进行过滤复制:

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

最新更新