ArrayIndexOutOfBoundsException when doing removeAt in map

3 answers

I try to remove a value from a map when unchecked but for some reason, it gives me an IndexOutOfBoundsException

itemView.checkBox.setOnCheckedChangeListener { buttonView, isChecked ->     item.isChecked = isChecked     if(isChecked){      map.put(position,true)     } else {         map.removeAt(position)     } } 

Here I have 2 checkboxes, when I check both is ok. When I uncheck the first one is ok, but when I try to uncheck also the second one it crashes with this error

 java.lang.ArrayIndexOutOfBoundsException: src.length=11 srcPos=2 dst.length=11 dstPos=1 length=-1 

The problem is at map.removeAt(position) but I don't know why it is failing because that position is an element from the array that actually exists.

I'm using a SparseBooleanArray.

Received answers to this question:
The best answer according to the author of the question:

Your code doesn't show where position is being set, but if I had to guess, you probably need to be doing position - 1

Remember that your arrays are 0 indexed!

The problem is not the position of the array as I said, because this array never changes (I never delete any items on it, just removing values on the map that contains this mapped booleans values)

So the problem was in removeAt(position)


I have a Map array with 2 values

0 - true 1 - true 

If I do map.RemoveAt(0) now I have

1 - true (actually in position 0 right now) 

but now if I try to do again map.removeAt(1) there is not element in position 1 so that is why is outbounded

I have solved it by removing by key in the map


So this will remove that 1 - true value and just the values with true as the value of that map

I saw the answer that you posted. Yes, you have figured that out correctly. You were getting the IndexOutOfBoundException because the position that you are looking for was already removed.

However, you do not have to use the key-value pair to remove that element from your map. It reduces the scalability of your Map object as somewhere down the road, the value might be changed and if you are not aware of that change, you might run into a similar problem, where the data will not be removed. Let us take the following example.

0 - true 1 - true

Now somewhere you have changed the value for key 1 to false. Hence when you will call the map.remove(position, true) this will not find anything to remove.

I would recommend using the remove function with the key only. The following should suffice.

if (map.containsKey(position)) map.remove(position); 

I hope that helps!