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.
1 |
public E get(int index) |
The get
method returns the object element at the specified position of the vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
import java.util.Vector; public class JavaVectorGetElementExample { public static void main(String[] args) { Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); /* * To get the element from the specific index * of the vector, use the get method */ /* * this will return element located at * the index 2 i.e. "30" */ System.out.println( vNumbers.get(2) ); /* * this will return element located at * the index 4 i.e. "50" */ System.out.println( vNumbers.get(4) ); } } |
Output
1 2 |
30 50 |
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).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); /* * This will throw ArrayIndexOutOfBoundsException * because index is out of the range (index ends * at size - 1 index i.e. 4 not 5) */ System.out.println( vNumbers.get(5) ); |
Output
1 2 |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 5 at java.util.Vector.get(Unknown Source) |
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.
1 2 3 4 5 6 7 8 9 10 11 |
Vector<Integer> vNumbers = new Vector<Integer>(); vNumbers.add(10); vNumbers.add(20); vNumbers.add(30); vNumbers.add(40); vNumbers.add(50); for(int i = 0; i < vNumbers.size(); i++){ System.out.println( vNumbers.get(i) ); } |
Output
1 2 3 4 5 |
10 20 30 40 50 |
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