Java Vector removeElementAt()
Java Vector类的
removeElementAt()方法用于删除指定索引处的组件。向量中索引大于或等于给定索引的每个元素都向下移动。现在向量索引比以前的值小一个。
语法
下面是
removeElementAt()方法的声明:
Public void removeElementAt(int index)
参数
DataType |
参数 |
说明 |
必需/可选 |
int |
索引 |
它是将被删除的对象的索引。必需 |
返回
此方法不返回任何内容。
异常
IndexOutOfBoundsException -如果数组的索引为数组,则此方法抛出异常。超出范围,即(index <0 || index> = size())。
兼容版本
Java 1.2及更高版本
示例1
import java.util.*;
public class VectorRemoveElementAtExample1 {
public static void main(String arg[]) {
//Create an empty vector
Vector<Integer> vec = new Vector<>();
//Add elements in the vector
vec.add(1);
vec.add(2);
vec.add(3);
vec.add(4);
vec.add(5);
vec.add(6);
//Displaying the vector element
System.out.println("Vector element before removal: " +vec);
//Remove an element
vec.removeElementAt(5);
//Displaying the vector element again
System.out.println("Vector element after removal: " +vec);
}
}
输出:
Vector element before removal: [1, 2, 3, 4, 5, 6]
Vector element after removal: [1, 2, 3, 4, 5]
示例2
import java.util.*;
public class VectorRemoveElementAtExample2 {
public static void main(String arg[]) {
//Create an empty Vector
Vector<String> vec = new Vector<>();
//Add elements to the Vector
vec.add("Rahul");
vec.add("Karan");
vec.add("Rahul");
vec.add("Rohan");
//Printing the elements of the Vector
System.out.println("The elements of a Vector before removal: "+vec);
//Removing the element at index 2
vec.removeElementAt(2);
//Printing the elements of the Vector again
System.out.println("The elements of a vector after removal: "+vec);
}
}
输出:
The elements of a vector before removal: [Rahul, Karan, Rahul, Rohan]
The elements of a vector after removal: [Rahul, Karan, Rohan]
示例3
import java.util.*;
public class VectorRemoveElementAtExample3 {
public static void main(String arg[]) {
//Create an empty vector
Vector<Integer> vec = new Vector<>();
//Add elements in the vector
vec.add(9);
vec.add(8);
vec.add(7);
//Remove an element
vec.removeElementAt(50);
//Displaying the vector element after removal
System.out.println("Vector element after removal: " +vec);
}
}
输出:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 50 >= 3
at java.base/java.util.Vector.removeElementAt(Vector.java:579)
at myPackage.VectorRemoveElementAtExample3.main(VectorRemoveElementAtExample3.java:12)