Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

elementat
vector
java
communitycreator

What is the Vector.elementAt method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The elementAt method of the Vector class is used to get the element at a specific index of the vector object.

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

Syntax

public E elementAt(int index)

Argument

The index is the index of a vector from which the element is to be fetched. The index should be positive and less than the size of the vector object. Otherwise, ArrayIndexOutOfBoundsException will be thrown.

This means:

index >= 0 && index < size()

Return value

This method returns the element present at the passed index.

Working example

Please click the “Run” button below to see how the elementAt method works.

import java.util.Vector;
class RemoveAll {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.add(1);
vector.add(2);
vector.add(3);
System.out.println("The Vector is: " + vector);
// Print first element
System.out.println("Element at index 0 : " + vector.elementAt(0));
System.out.println("Element at index 1 : " + vector.elementAt(1));
System.out.println("Element at index 2 : " + vector.elementAt(2));
}
}

Explanation

In the code above,

  • Line 5: We created a vector object.

  • Lines 8 - 10: We added three elements (1,2,3) to the above created vector object.

  • Lines 15 - 17: We used the elementAt method of the vector object to get the element present at index 0, 1, and 2.

RELATED TAGS

elementat
vector
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring