This week's book giveaway is in the Cloud/Virtualizaton forum.We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Java Vector simple Q

Stefan MÃ¼llerheim
Greenhorn
Posts: 12
hi an easy question,

if a Vector is new to built , first the capacity size is to init.

now, if i try to set a position with an object i am going to get an "out of range" error.

the solution is simple: in a loop with my capacity size, every position have first to set with "null".

but that makes no sin for me.

why is it necessary to init the capacity, when it is not usable? where is my fault?

Henry Wong
author
Marshal
Posts: 21126
78
Stefan Muellerheim wrote:
why is it necessary to init the capacity, when it is not usable? where is my fault?

It is not necessary to init the capacity -- the vector will grow as needed as you add more elements. The reason that you may want to init the capacity is if you know how many elements you will be using, and you don't want the vector wasting time growing the capacity for you.

The capacity is just the amount of memory reserved for you. It is not the number of elements in the vector. And it is not possible to make an element the 5th element when there aren't four elements to put it after.

Henry

Wouter Oet
Saloon Keeper
Posts: 2700
Remember that you're setting the capacity not the size. The initial size is 0 and the capacity is 20. So when you're trying to insert a new element at a higher then 0 you'll get an Exception.

Stefan MÃ¼llerheim
Greenhorn
Posts: 12
thanks, now it's easy to understand.

a Vector is only at a specified position settable if there is an object already.
a Vector have to set from the beginning always.
if any position, then it has to filled up with 'null'.
if any position, size() is not usable, due to the dummy-objects.

Vector should make it possible to set an(y) object to any position (without adding 'null').

Wouter Oet
Saloon Keeper
Posts: 2700
Are you sure that you want a Vector and not an ArrayList? They are the same but the methods of the Vector are synchronized. You could also use a Map with an Integer key.

Rob Spoor
Sheriff
Posts: 20532
54
Stefan Muellerheim wrote:Vector should make it possible to set an(y) object to any position (without adding 'null').

Then what should it do with the indexes in between? What should the elements at indexes 0 to 4 be?

An easy way is to simply create a utility method: