Reputation: 98
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?
Upvotes: 0
Views: 1232
Reputation: 7838
Just as others mentioned, you cannot remove(Object o)
in a for loop
, you have to do that removal using Iterator
as
public void removeAllHandlers() {
synchronized (handlers) {
Iterator<String> keyIterator = handlers.keySet().iterator();
while (keyIterator.hasNext()) {
RequestData requestData = handlers.get(keyIterator.next());
if(iDontWant(requestData)) {
keyIterator.remove();
}
}
}
}
Upvotes: 0
Reputation: 2105
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();
}
}
Upvotes: 2
Reputation: 2404
You are modifying the ArrayMap that your are iterating over. This is an anti-pattern in Java and will cause error. I recommend you using another ArrayMap for your modifications.
Upvotes: 0
Reputation: 211
Try this
private ArrayMap<String,RequestData> handlers = new ArrayMap<>();
public void removeAllHandlers() {
synchronized (handlers) {
ArrayMap<String,RequestData> tempHandlers = handlers;
for (String s : tempHandlers.keySet()) {
handlers.remove(s);
}
}
}
Upvotes: 0