Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterator isEmpty() call causing noSuchElement exception?

I currently have the following code

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();
        }
    }
}

However, I get a NoSuchElementException crash on the line

tile = visibleTiles.keySet().iterator().next();

Is there a big difference in using the isEmpty() method and calling a hasNext() call? I know that hashmaps do not have a hasNext() call so I did the following:

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();
        }
    }
}

Obviously, I know that I should just run the app and see if it crashes, but the issue is that it's difficult to reproduce the problem.

Thanks!

like image 972
kevinl Avatar asked Mar 06 '26 20:03

kevinl


1 Answers

visibleTiles.isEmpty()

just checks whether map is empty (or) it has any elements.

ile = visibleTiles.keySet().iterator().next();

retrieves next element from iterator.

You need to do hasNext() check before doing next() on iterator.

hasNext() javadoc says

Returns true if the iteration has more elements. (In other words, returns true if next would return an element rather than throwing an exception.)

so, if no element is available and call next() on iterator will return NoSuchElementException.

On top of this, I think you really would like to do NOT empty check

while (!visibleTiles.isEmpty())) {
....
}
like image 91
kosa Avatar answered Mar 08 '26 10:03

kosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!