gpt4 book ai didi

Java 集合 : Compare elements in collection with each other and remove in one cycle

转载 作者:搜寻专家 更新时间:2023-11-01 01:58:11 25 4
gpt4 key购买 nike

比如说,我有一些地理位置的集合(格式为 Country > Region [ > Town [ > District]]),我想删除相互重叠的位置(例如,Europe > GermanyEurope > Germany > DresdenEurope > 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com