insertElementAt(K, int): This method is available in java.util.Vector class of Java.
Syntax:
void java.util.Vector.insertElementAt(K obj, int index)
This method takes two arguments. This method inserts the specified object as a component in this vector at the specified index.
Note: Each component in this vector with an index greater or equal to the specified index is shifted upward to have an index one greater than the value it had previously.
Parameters: Two parameters are required for this method.
obj: the component to insert.
index: where to insert the new component.
Throws:
ArrayIndexOutOfBoundsException - if the index is out of range(index < 0 || index > size())
Approach 1: When no exception
Java
import java.util.Vector;public class VectorinsertElementAt {public static void main(String[] args) {Vector<String> vector = new Vector<>();vector.add("Hello");vector.add("Java");vector.add("C++");vector.add("Program");int index = 1;String obj = "Python";vector.insertElementAt(obj, index);System.out.println(vector);}}
Output:
[Hello, Python, Java, C++, Program]
Approach 2: ArrayIndexOutOfBoundsException
Java
import java.util.Vector;public class VectorinsertElementAt {public static void main(String[] args) {Vector<String> vector = new Vector<>();vector.add("Hello");vector.add("Java");vector.add("C++");vector.add("Program");int index = 5;String obj = "Python";vector.insertElementAt(obj, index);System.out.println(vector);}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 > 4 at java.base/java.util.Vector.insertElementAt(Vector.java:589)
No comments:
Post a Comment