programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Paul Clapham
• Bear Bibeault
• Jeanne Boyarsky
Sheriffs:
• Ron McLeod
• Tim Cooke
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Jj Roberts
• Stephan van Hulst
• Carey Brown
Bartenders:
• salvin francis
• Scott Selikoff
• fred rosenberger

# Vector.remove()

Ranch Hand
Posts: 268
Hi all.
I added 3 elements to a vector. I am trying to remove them one by one randomly. Presently i used a for loop and gave vector.remove(i). I am getting a array index out of range error. Anybody can say y?

Thanks
alexander

Sheriff
Posts: 22018
108
This has nothing to do with I/O, so I'm stealing this to Java in General.

You are calling remove but you probably still assume that the size has remained the same. However, when you remove an element the size of course changes. A very common mistake is the following:
This will remove every other element; you first remove element 0, but old element 1 becomes element 0. You then remove element 1 which was previously element 2, etc.

Can you show us your loop?

Marshal
Posts: 25956
69
To start with the elements are numbered 0, 1, 2. Let's suppose that you remove 1. So now you have 0 and 2 still to remove? No. Now the elements are numbered 0, 1.

I'm guessing your problem has something to do with that.

Ranch Hand
Posts: 105
How are you generating i? If it is generated randomly, it needs to be modded (using %) to fall within 0 and 2 (actually, 0 and length-of-vector - 1).

Bartender
Posts: 2698
130

I added 3 elements to a vector. I am trying to remove them one by one randomly. Presently i used a for loop and gave vector.remove(i). I am getting a array index out of range error. Anybody can say y?

Thanks
alexander

Just do one simple thing:
add this line of code and tell use the output: