Java Vector insertElementAt()
Java Vector类的
insertElementAt()方法用于将指定的对象作为组件插入此Vector中。在指定的索引处。向量中索引大于或等于给定索引的每个分量都向上移动。现在,向量索引比以前的值大一个。
语法
以下是
insertElementAt()的声明。方法:
public void insertElementAt(E obj, int index)
参数
参数 |
说明 |
必需/可选 |
obj |
这是将要插入的元素。 |
必需 |
index |
这是我们将插入新元素的索引。 |
必需 |
返回
insertElementAt()方法不返回任何内容。
异常
ArrayIndexOutOfBoundsException -如果索引超出范围,此方法将引发异常范围,即索引<0 || index> = size()。
兼容性版本
Java 1.2及更高版本
示例1
import java.util.*;
public class VectorInsertElementAtExample1 {
public static void main(String arg[]) {
//Create an empty vector
Vector<Integer> vec = new Vector<>();
//Add element in the vector
vec.add(10);
vec.add(20);
vec.add(30);
vec.add(40);
vec.add(50);
//Printing the element
System.out.println("Element in vector before insertion = "+vec);
//Insert the element at 2nd position
vec.insertElementAt(700, 2);
System.out.println("Element in vector after insertion = "+vec);
}
}
输出:
Element in vector before insertion = [10, 20, 30, 40, 50]
Element in vector after insertion = [10, 20, 700, 30, 40, 50]
示例2
import java.util.*;
public class VectorInsertElementAtExample2 {
public static void main(String arg[]) {
//Create an empty vector
Vector < String > vec = new Vector < String > ();
//Add elements in the vector
vec.add("Java");
vec.add("Ruby");
vec.add("Android");
vec.add("Python");
//Print the elements of this vector
System.out.println("Components of vector: ");
for (String program : vec) {
System.out.println(" " +program);
}
//Insert the element at 2nd position
vec.insertElementAt("PHP", 1);
System.out.println("Components of vector after insertion = ");
for (String program : vec) {
System.out.println("" +program);
}
}
}
输出:
Components of vector:
Java
Ruby
Android
Python
Components of vector after insertion =
Java
PHP
Ruby
Android
Python
示例3
import java.util.*;
public class VectorInsertElementAtExample3 {
public static void main(String arg[]) {
//Create an empty vector
Vector < String > colors = new Vector < String > ();
//Add elements in the vector
colors.add("White");
colors.add("Green");
colors.add("Black");
//Print the elements of this vector
System.out.println("Color elements in vector: " +colors);
//Insert the element at 2nd position
colors.insertElementAt("Red", 12);
System.out.println("Element in vector after insertion = "+colors);
}
}
输出:
Color elements in vector: [White, Green, Black]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12 > 3
at java.base/java.util.Vector.insertElementAt(Vector.java:619)
at myPackage.VectorInsertElementAtExample3.main(VectorInsertElementAtExample3.java:14)