Thursday, February 14, 2008

Getting ArrayIndexOutofBounds exception while removing selected indices from a list through a loop????

Consider this scenario..u have a list containing some "n" elements and u want to remove some elements say with indices 3,6,12 ,...
See the following code:

int indices[100] ; // indices array contains list of indices of elements to be removed from list

for(int i=0;i namesList.remove(indices[i]); // namesList is a list that contains // //elements
Now if u feel that above code is fyn...u r in a soup ;-) Try executing it ...U will get ArrayIndexOutofBoundsException...
Wonder yyyy??????Its silly actually.
The key is when u remove an element from a list...the remaining elements will push each one a level forward.. say u removed an element with index 5 , now 6 element will become 5.. and 7 th element will become 6 element ..
So while removing items in a loop the logic should be chosen accordingly...

1 comment:

Anil said...

sorry..I had some minor mistakes in the sample code above earlier and i fixed it now...gud thing is no one pointed out;-)