Create New Vector Object in Java Example (Vector Constructors)

This example shows how to create a new Vector object in Java. This example also shows how to create a new object of Vector using various constructors.

How to create a new object of Vector in Java?

The Java Vector class provides several constructors using which we can create new objects of it.

1. How to create a new and empty Vector?

The default no-argument Vector constructor creates a new and empty vector object.

The vector object created using the default constructor has the initial capacity of 10 and a capacity increment of 0.

The above statement will create a new vector object of type Integer having initial capacity of 10 elements.

2. How to create with custom initial capacity and capacity increment?

If you want to specify the initial capacity of the vector object at the creation time, you can use the below given overloaded constructor.

It creates a new object with the specified initial capacity and the default capacity increment i.e. 0.

The above statement will create a new vector whose elements will be of type Integer and having the initial capacity of 30 and capacity increment of 0.

If you want to specify both, the initial capacity and capacity increment, you can use below given overloaded constructor.

It will create a new object with the specified initial capacity and capacity increment.

3. How to create a vector from other list objects?

The Vector class provides an overloaded constructor that accepts a Collection object as an argument.

It will create a new Vector object having all the elements of the specified collection object. The order of the elements will be the same that is returned by the collection object’s iterator. The capacity of this vector object will be sufficient to hold all the elements of the collection object.

The below given example shows how to create a new Vector object from an ArrayList object using this constructor.

Output

This example is a part of the Vector in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Vector Documentation

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

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