Java.util.Vector 类

java.util.Vector.setElementAt()方法用于将向量指定索引处的分量设置为是指定的对象。该位置的前一个组件将被丢弃。

语法

public void setElementAt(E obj, int index)

这里,E是容器维护的元素类型。

参数

obj 指定要设置的对象。
index 指定要设置的组件的索引号。

返回值

void类型。

异常

如果索引超出范围,即(index < 0 || index > size()),则抛出 IndexOutOfBoundsException

示例:

在下面的示例中,java.util.Vector.setElementAt()方法用于将向量的指定索引处的元素设置为指定元素。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建向量
    Vector<Integer> MyVector = new Vector<Integer>();

    //填充向量
    MyVector.add(10);
    MyVector.add(20);
    MyVector.add(30);
    MyVector.add(40);
    MyVector.add(50);

    System.out.println("Before method call, MyVector contains: " + MyVector);
    MyVector.setElementAt(1000, 1);
    System.out.println("After method call, MyVector contains: " + MyVector);    
  }
}

上述代码的输出将是:

Before method call, MyVector contains: [10, 20, 30, 40, 50]
After method call, MyVector contains: [10, 1000, 30, 40, 50]