Dan*_*don 1 java iterator findbugs treemap sonarqube
这是一个类似的问题[ FindBugs警告:使用keySet迭代器而不是entrySet迭代器的效率低下
但是,我想尝试做一些不同的事情.我目前的代码在这里:
for (Double key2 : sortedPolygons.keySet()) {
if (sortedPolygons.get(key2).getExteriorRing().equals(hole)) {
sortedPolygons.remove(key2);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
在链接中执行类似解决方案的操作不起作用.以下是所述解决方案的实现:
for(Map.Entry<Double, Polygon> entry : sortedPolygons.entrySet()) {
if (entry.getValue().getExteriorRing().equals(hole)) {
.....
Run Code Online (Sandbox Code Playgroud)
这里的问题是我试图删除该条目.没有entry.remove().如何在没有FindBugs错误的情况下替换我的第一个代码块:
低效使用keySet迭代器而不是entrySet迭代器 - >
此方法使用从keySet迭代器检索的键访问Map条目的值.在map的entrySet上使用迭代器更有效,以避免Map.get(键)查找.
需要注意的是TreeMap,底层结构是,并且无法更改.
我无法理解你的理由:在你使用的第一个片段中
sortedPolygons.remove(key2);
Run Code Online (Sandbox Code Playgroud)
删除密钥.没有什么能阻止你在第二个片段中做同样的事情:
sortedPolygons.remove(entry.getKey());
Run Code Online (Sandbox Code Playgroud)
无论你如何迭代,这都将导致ConcurrentModificationException无论如何,因为对于大多数集合,除了使用它的迭代器之外,你不能在迭代它时修改它.
从javadoc引用:
所有这个类的"集合视图方法"返回的集合的迭代器方法返回的迭代器是快速失败的:如果在创建迭代器之后的任何时候对映射进行结构修改,除非通过迭代器自己的删除方法,迭代器将抛出ConcurrentModificationException.
所以代码应该是:
for (Iterator<Map.Entry<Double, Polygon>> it = sortedPolygons.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<Double, Polygon> entry = it.next();
if (entry.getValue().getExteriorRing().equals(hole)) {
it.remove();
// if you want to exit the loop as soon as you found a match:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2997 次 |
| 最近记录: |