Java Vector insertElementAt() 方法

2025年3月24日 | 阅读时间:2 分钟

Java Vector 类的 insertElementAt() 方法用于在该向量的指定索引处插入指定的对象作为组件。向量中索引大于或等于给定索引的每个组件都将向上移动。现在,向量的索引比之前大了一。

语法

以下是 insertElementAt() 方法的声明

参数

参数描述必需/可选
obj这是要插入的元素。必需
索引这是插入新元素的位置索引。必需

返回

insertElementAt() 方法不返回任何值。它仅在给定索引处插入一个元素。

异常

ArrayIndexOutOfBoundsException- 如果索引超出范围,即 index < 0 || index >= size(),则此方法将抛出异常。

兼容版本

Java 1.2 及以上版本

示例 1

输出

Element in vector before insertion = [10, 20, 30, 40, 50]
Element in vector after insertion = [10, 20, 700, 30, 40, 50]

示例 2

输出

Components of vector: 
 Java
 Ruby
 Android
 Python
Components of vector after insertion = 
 Java
 PHP
 Ruby
 Android
 Python

示例 3

输出

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)
 
下一主题Java Vector