add(int, K): This method is available in java.util.Vector class of Java.
Syntax:
void java.util.Vector.add(int index, K element)
This method takes two arguments. This method inserts the specified element at the specified position in this Vector. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Parameters: Two parameters are required for this method.
index: index at which the specified element is to be inserted.
element: the element to be inserted.
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 Vectoradd2 {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 element = "Python";vector.add(index, element);System.out.println(vector);}}
Output:
[Hello, Python, Java, C++, Program]
Approach 2: ArrayIndexOutOfBoundsException
Java
import java.util.Vector;public class Vectoradd2 {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 element = "Python";vector.add(index, element);System.out.println(vector);}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 > 4 at java.base/java.util.Vector.insertElementAt(Vector.java:589) at java.base/java.util.Vector.add(Vector.java:827)
No comments:
Post a Comment