Get Vector elements
There are many methods to retrieve or get element from Vector
Object get(int index);
Object firstElement();
Object elementAt(int index);
Object get(int index)
We can use get(int index) method for retrieving the element from Vector
It returns the value present at the specified index
This method throws IndexOutOfBoundsException if the index is less than zero or greater than the size of the Vector
Example :
- import java.util.*;
- public class VectorGetElement {
- public static void main(String[] args) {
- Vector<String> vector = new Vector<String>();
- vector.add("java");
- vector.add("c++");
- vector.add("python");
- vector.add("c");
- System.out.println("First element of the Vector: "+vector.get(0));
- System.out.println("Third element of the Vector: "+vector.get(2));
- }
- }
import java.util.*; public class VectorGetElement { public static void main(String[] args) { Vector<String> vector = new Vector<String>(); vector.add("java"); vector.add("c++"); vector.add("python"); vector.add("c"); System.out.println("First element of the Vector: "+vector.get(0)); System.out.println("Third element of the Vector: "+vector.get(2)); } }
Object firstElement()
We can use this method to retrieve first element from the vector
Example :
- import java.util.*;
- public class VectorFirstElement {
- public static void main(String[] args) {
- Vector<String> vector = new Vector<String>();
- vector.add("java");
- vector.add("c++");
- vector.add("python");
- vector.add("c");
- System.out.println("First element of the Vector: "+vector.firstElement());
- }
- }
import java.util.*; public class VectorFirstElement { public static void main(String[] args) { Vector<String> vector = new Vector<String>(); vector.add("java"); vector.add("c++"); vector.add("python"); vector.add("c"); System.out.println("First element of the Vector: "+vector.firstElement()); } }
Object elementAt(int index)
This method is very similar to first method get(int index)
It returns element at the specified index
Example :
- import java.util.*;
- public class VectorElementAt {
- public static void main(String[] args) {
- Vector<String> vector = new Vector<String>();
- vector.add("java");
- vector.add("c++");
- vector.add("python");
- vector.add("c");
- System.out.println("Element of the Vector at index 2: "+vector.elementAt(2));
- }
- }
import java.util.*; public class VectorElementAt { public static void main(String[] args) { Vector<String> vector = new Vector<String>(); vector.add("java"); vector.add("c++"); vector.add("python"); vector.add("c"); System.out.println("Element of the Vector at index 2: "+vector.elementAt(2)); } }