public
void add(int index, E element)
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).
import java.util.*; class VectorAddAtIndex{ public static void main(String args[]){ Vector<Integer> myVector = new Vector<> (); /* Add Elements to myVector */ myVector.add(10); myVector.add(20); myVector.add(30); myVector.add(40); System.out.println("Elements in myVector are"); System.out.println(myVector); System.out.println("\nAdd 50 at the front\n"); myVector.add(0, 50); System.out.println("Elements in myVector are"); System.out.println(myVector); } }
Output
Elements in myVector are [10, 20, 30, 40] Add 50 at the front Elements in myVector are [50, 10, 20, 30, 40]
1. Throws
ArrayIndexOutOfBoundsException if the index is out of range
import java.util.*; class VectorAddArrayIndexOut{ public static void main(String args[]){ Vector<Integer> myVector = new Vector<> (); /* Add Elements to myVector */ myVector.add(10); myVector.add(20); myVector.add(30); myVector.add(40); System.out.println("Elements in myVector are"); System.out.println(myVector); System.out.println("\nAdd 0 at 50th index\n"); myVector.add(50, 0); System.out.println("Elements in myVector are"); System.out.println(myVector); } }
Output
Elements in myVector are [10, 20, 30, 40] Add 0 at 50th index Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50 > 4 at java.util.Vector.insertElementAt(Vector.java:594) at java.util.Vector.add(Vector.java:810) at VectorAddArrayIndexOut.main(VectorAddArrayIndexOut.java:15)
No comments:
Post a Comment