我目前有以下代码
while (!visibleTiles.isEmpty())) {
tile = visibleTiles.keySet().iterator().next();
if (tile != null){
bitmap = visibleTiles.remove(tile);
if(bitmap != null && !containsKey(tile)){ //safe to recycle if tile cache is not actively holding it
bitmap.recycle();
}
}
}
但是,我在线上遇到了 NoSuchElementException 崩溃
tile = visibleTiles.keySet().iterator().next();
使用 isEmpty() 方法和调用 hasNext() 调用有很大区别吗?我知道 HashMap 没有 hasNext() 调用,所以我执行了以下操作:
while (visibleTiles.keySet().iterator().hasNext()) {
tile = visibleTiles.keySet().iterator().next();
if (tile != null){
bitmap = visibleTiles.remove(tile);
if(bitmap != null && !containsKey(tile)){ //safe to recycle if tile cache is not actively holding it
bitmap.recycle();
}
}
}
显然,我知道我应该只运行该应用程序并查看它是否崩溃,但问题是很难重现该问题。
谢谢!
最佳答案
visibleTiles.isEmpty()
只是检查 map 是否为空(或)是否有任何元素。
ile = visibleTiles.keySet().iterator().next();
从迭代器中检索下一个元素。
在对迭代器执行 next()
之前,您需要执行 hasNext()
检查。
hasNext()
javadoc说
Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)
因此,如果没有可用元素并在迭代器上调用 next()
将返回 NoSuchElementException
。
最重要的是,我想你真的不想做空检查
while (!visibleTiles.isEmpty())) {
....
}
关于java - 迭代器 isEmpty() 调用导致 noSuchElement 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13053195/