Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

What is the Vector.setElementAt 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 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.

The setElementAt method of the Vector class can be used to replace the element present at the specific index of the vector object.

Syntax

public void setElementAt(E obj,int index)

Argument

This method takes two arguments.

  1. The element to be replaced in the vector object.

  2. The index at which the new element is to be replaced. The index should be positive and less than the size of the vector object. Otherwise, ArrayIndexOutOfBoundsException will be thrown.

index >= 0 && index < size()

Return value

This method doesn’t return any value.

Code

import java.util.Vector;
class SetElementAt {
public static void main( String args[] ) {
// Creating Vector
Vector<Integer> vector = new Vector<>();
// add elememts
vector.add(10);
vector.add(40);
vector.add(30);
System.out.println("The Vector is: " + vector); // [10,40,30]
vector.setElementAt(20, 1); // [10,20,30]
System.out.println("\nAfter calling setElementAt(20,1). The Vector is: " + vector);
}
}

Explanation

In the code above:

  • In line 5: We created a vector object.

  • In lines 8 to 10: We added three elements, 10,40,30, to the created vector object.

  • In line 14: We used the setElementAt method of the vector object to replace the element present at index 1 with the value 20. Now, the vector will be 10,20,30.

RELATED TAGS

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