Add Element to Vector

In the previous post, we have seen what is Vector in java. In this post, we will see how to add element to vector.

There are 3 ways, we can create vector as given below.

#1 Vector vec = new Vector();

It creates an empty vector with default size of 10. If a 11th element will be added to the vector, it will be re-sized to doubles of its capacity. That means if it has capacity, it will be re-sized to 20 when inserting the 11th element.

#2  Vector object= new Vector(int initialCapacity)

e.g.  Vector vec = new Vector(5)

It will create a vector of size of 5 elements.

#3 Vector vec = new vector(int initialcapacity, int capacityIncrement)

e.g.  Vector vec = new Vector(3,5)

It has 2 arguments. First intialcapacity is 3 which means it creates a vector of size 3. Second argument capacityIncrement is 5 which means if vector is full then at insertion of next element it will be incremented with the given capacity i.e. 5. So it will become 8 (3+5).


The method to add element is ‘addElement()’.

Example:

Output:

All cars : [BMW, Honda, Audi] Vector size : 3
Vector Capacity : 3
Vector size after adding more elements than its size : 5
Vector Capacity : 6


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Print Friendly, PDF & Email
Vector in java
Add Element at the specified index in Vector
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. September 20, 2015

    […] Add an element to Vector […]

Leave a Reply

Your email address will not be published. Required fields are marked *