Jiew Meng
Jiew Meng

Reputation: 88207

Why can't I insert an element at specified index with a Vector?

I tried

cache = new Vector<CacheBlock>(1024);
...
cache.add(10, blk); // gives index out of bounds

So is it impossible to insert (into specified index) into an empty list? Or how might I fill up all elements if the Vector, with null or otherwise, so I can accomplish this?

Upvotes: 2

Views: 488

Answers (2)

David Heffernan
David Heffernan

Reputation: 612993

Vectors are contiguous. They must have elements at each index from 0 to size-1. There cannot be any gaps. Thus you cannot insert at an index outside the current bounds of the vector because that would leave holes.

So, if you want to insert at index 10, you have to first ensure that the list is populated with at least 10 items. You can use setSize to do this (emphasis mine):

Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector.

Upvotes: 2

Steve Claridge
Steve Claridge

Reputation: 11080

You could use setSize() to make sure your cache is big enough before you insert elements:

setSize

public void setSize(int newSize)

Sets the size of this vector. If the new size is greater than the current size, new null items are added to the end of the vector. If the new size is less than the current size, all components at index newSize and greater are discarded.

cache = new Vector<CacheBlock>(1024);
cache.setSize(11);
cache.add(10, blk);

Upvotes: 4

Related Questions