Skip to content

Java Vector Get Elements Example

This example shows how to get elements from Vector in Java. This example also shows how to get the elements using the element index and the get method.

How to get elements from the Vector using the get method?

The Vector get method returns an element located at the specified index of the vector object.

The get method returns the object element at the specified position of the vector.

Output

The Vector is an index based data structure. The Vector index starts from 0 and ends at the size of the Vector – 1 index. In other words, the first element of the Vector is located at index 0 and the last element of the vector is located at the index (vector size – 1).

If the index specified in the get method is not in this range, it will throw ArrayIndexOutOfBoundsException exception i.e. if the specified (index < 0 or index >= vector size).

Output

We can use the Vector get method along with the size method and a for loop to get all elements from the vector object as given below.

Output

We initialized the counter variable i with 0 to start accessing the elements from index 0 of the vector in the for loop. The for loop condition checks if the counter variable i is less than the size, so it will return true up to the value (size – 1), that’s where the last element of the vector object is located.

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

Leave a Reply

Your email address will not be published.