3 examples to learn Java vector in 30 minutes

What is the Java vector class?

The vector is a class in Java that implements the dynamic arrays. The standard arrays are not dynamic. That means once created you cannot add or remove elements. Whereas, the vector allows to grow or shrink arrays at the run time.

Create and print vector example

A few main points about Java vector class

  • Vectors implement dynamic arrays.
  • Before Java 2, the Java provided ad hoc classes. The vector class is one of those.
  • Vector class is like the ArrayList in that it allows dynamic arrays.
  • Vector is different to ArrayList in that the vector is synchronized. Also, the vectors Java class provides the legacy methods that are not part of the collections framework.

Vector size method example

How to use vector class

In order to use the Vector class in your projects you must import this class as follows:

Import java.util.Vector;

How to declare a vector

After importing the vector class, it is time to declare an object of vector class. The default way is:

Vector array_name = new Vector();

An array “array_name” of the ten size is created. The Vector default constructor creates an array of the ten size.

Other methods of declaration

You may also use other constructors of Vector to declare an array as follows:

(1)    By specifying size:

Vector array_name = new Vector (int size)

An array with the given number in the int will be created.

(2)    Create Vector from the other collection type:

Vector array_name = new Vector (Collection c) ;

Example of creating and printing vector in Java

The example below shows creating a Vector object. It adds five elements and then a for loop is used to display the Vector elements.

Java vector example

Experience this online



The output will be:

10

20

30

40

50

Useful methods of Vector

Following are a few useful methods of Vectors.

Example of adding Array elements at specific index

The following example shows creating a Java Vector object. It adds elements to the specific index position by using the add method.

Java vector

Experience this online



The output will be:

0

10

20

25

30

40

50

Using Vector size method example

The following example shows how to use the size method of the vector.



Experience this online

The output will be:

The size of Vector is: 5

First, we created a vector, Intarr. After that, we added five elements by using the add method of Vector. Finally, we used the System.out.println statement to display the total size by using the vector’s size method.

Further reading: Java ArrayList  | Java arrays


Was this article helpful?

Related Articles

Leave A Comment?