比如说,我有一些地理位置的集合(格式为 Country > Region [ > Town [ > District]]
),我想删除相互重叠的位置(例如,Europe > Germany
与 Europe > Germany > Dresden
和 Europe > Germany > Hamburg
重叠,因此必须删除最后两个)。我看到我需要两个迭代器实例来制作这样的东西:
final Iterator<Location> outerIterator = locations.newIterator();
while (outerIterator.hasNext()) {
final Location outer = outerIterator.next();
final Iterator<Location> innerIterator = locations.newIterator();
while (innerIterator.hasNext()) {
final Location inner = innerIterator.next();
if (!inner.equals(outer)) {
if (inner.overlaps(outer)) outerIterator.remove();
else if (outer.overlaps(inner)) innerIterator.remove();
}
}
}
但我无法为同一个集合获取新的Iterator
。是我的算法不正确还是有正确的方法?
使用来自 answer provided 的建议的最终代码通过 Carl Smotricz看起来像这样:
final Iterator<JobLocation> outerIterator = locations.iterator();
while (outerIterator.hasNext()) {
final JobLocation outer = outerIterator.next();
final Iterator<JobLocation> innerIterator = locations.iterator();
while (innerIterator.hasNext()) {
final JobLocation inner = innerIterator.next();
if (!inner.equals(outer) && inner.overlaps(outer)) {
outerIterator.remove();
break;
}
}
}
最佳答案
您确定要在内循环中递增 outerIterator 吗?
关于Java 集合 : Compare elements in collection with each other and remove in one cycle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3235627/