Search code examples
javaandroidindexoutofboundsexceptionarray-map

Java ArrayIndexOutOfBounds Exception on array map


I have a code that iterates on ArrayMap keys, and I got an Array Index Out Of Bounds Exception from unknown reason

From Crashalytics:

Fatal Exception: java.lang.ArrayIndexOutOfBoundsException
length=56; index=56
android.util.ArrayMap$1.colGetEntry (ArrayMap.java:763)
android.util.MapCollections$ArrayIterator.next (MapCollections.java:55)

The code looks like that:

private ArrayMap<String,RequestData> handlers = new ArrayMap<>();

public void removeAllHandlers() {
    synchronized (handlers) {
        for (String s : handlers.keySet()) {
            handlers.remove(s);
        }
    }
}

the Exception happened at this line: for (String s : handlers.keySet())

Any clue what am I doing wrong?


Solution

  • You cannot remove from a Map or a List while iterating. Use the internal clear method of the Map/List. For instance, handlers.clear();

    Code:

    private ArrayMap<String,RequestData> handlers = new ArrayMap<>();
    
    public void removeAllHandlers() {
            synchronized (handlers) {
                    handlers.clear();
            }
        }