2 回答

TA貢獻1798條經(jīng)驗 獲得超7個贊
您基本上需要保留對最后添加的對象的引用。如果您當前嘗試添加的對象是相同的,那么您應(yīng)該跳過它。
以下是使用您的代碼的樣子:
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;
}

TA貢獻1810條經(jīng)驗 獲得超4個贊
根據(jù)您的描述,您的代碼似乎沒有做您想做的事情。
我想要的是刪除列表中彼此相鄰的重復(fù)點,因此列表看起來像 { a, b, a, c, a }
以下代碼應(yīng)該可以完成工作:
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;
}
添加回答
舉報