• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

adeeb alexander wrote: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



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

 
Goodbye moon men. Hello tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic