简体   繁体   English

删除彼此相邻的重复项

[英]removing duplicates that are next to each other

I have a list: private static List<Point> pointList = new ArrayList<>(); 我有一个列表: private static List<Point> pointList = new ArrayList<>(); .

Point = object representing a point in 3D graph. Point =代表3D图形中一个点的对象。

I can compare Points with method: 我可以将点数与方法进行比较:

@Override
public boolean equals(Object o) {
    if (this == o)
        return true;
    if (o == null || getClass() != o.getClass())
        return false;
    Point point = (Point) o;
    return Arrays.equals(position, point.position);
}

Lets say my list looks like that: { a1, a2, b1, a3, c1, c2, a4 } 可以说我的列表如下:{a1,a2,b1,a3,c1,c2,a4}

All objects are different objects (a1 =/= a2..), but have same values ( a1, a2... representing exact same point on graph) 所有对象都是不同的对象(a1 = / = a2 ..),但是具有相同的值(a1,a2 ...表示图形上的完全相同的点)

What I want is to remove duplicated Points that are next to each other on list, so list would look like that { a, b, a, c, a } 我想要的是删除列表上彼此相邻的重复Points ,因此列表看起来像{a,b,a,c,a}

I tried: 我试过了:

public List<Point> getUniq() {
    List<Point> l = new ArrayList<>();
    for (int i = 0; i < pointList.size()-1; i++) {
        if (pointList.get(i).equals(pointList.get(i + 1))) {
            l.add(pointList.get(i));
        }
    }
    return l;
}

But I'm missing elements. 但是我缺少元素。

You basically need to keep reference to the last added object. 基本上,您需要保留对最后添加的对象的引用。 If the object that you are currently trying to add is the same, then you should skip it. 如果您当前尝试添加的对象是相同的,则应跳过它。

Here is how it would look like using your code: 使用您的代码的样子如下:

public List<Point> getUniq() {
    List<Point> result = new ArrayList<>();
    Point lastAdded = null;
    for (int i = 0; i < pointList.size(); i++) {
        if (!points.get(i).equals(lastAdded)) { // previously added point was different
            lastAdded = points.get(i); // update previously added
            result.add(lastAdded); // add to result
        }
    }
    return result;
}

Your code does not seem to do what you want according to your description. 根据您的描述,您的代码似乎没有执行您想要的操作。

What I want is to remove duplicated Points that are next to each other on list, so list would look like that { a, b, a, c, a } 我想要的是删除列表上彼此相邻的重复点,因此列表看起来像{a,b,a,c,a}

The following piece of code should do the work: 下面的代码应该可以完成工作:

public List<Point> getUniq() {
    List<Point> l = new ArrayList<>();
    l.add(pointList.get(0)); //the first element will always be added
    for (int i = 1; i < pointList.size(); i++) {
        if (!l.get(l.size()-1).equals(pointList.get(i))) {
            l.add(pointList.get(i));
        }
    }
    return l;
}

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

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