📜  Java中的向量 setElementAt() 方法与示例

📅  最后修改于: 2022-05-13 01:54:59.109000             🧑  作者: Mango

Java中的向量 setElementAt() 方法与示例

Java VectorsetElementAt()方法用于将该vector的指定索引处的组件设置为指定对象。该位置的前一个组件被丢弃。索引必须是大于或等于 0 且小于向量当前大小的值。

句法:

public void setElementAt(E element, int index)

参数:此函数接受两个参数,如上述语法所示,如下所述。

  • element :它将替换现有元素的新元素,并且与向量具有相同的对象类型。
  • index :这是整数类型,指的是要从向量中替换的元素的位置。

返回值:此方法不返回任何内容。

异常:如果索引超出范围 (index = size()),此方法将抛出ArrayIndexOutOfBoundsException

下面的程序说明了Java.util.Vector.setElementAt() 方法:

示例 1:

// Java code to illustrate setElementAt()
  
import java.io.*;
import java.util.*;
  
public class VectorDemo {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector vector
            = new Vector();
  
        // Use add() method to add elements in the vector
        vector.add("Geeks");
        vector.add("for");
        vector.add("Geeks");
        vector.add("10");
        vector.add("20");
  
        // Displaying the linkedvector
        System.out.println("Vector:"
                           + vector);
  
        // Using setElementAt() method to replace Geeks with GFG
        vector.setElementAt("GFG", 2);
        System.out.println("Geeks replaced with GFG");
  
        // Displaying the modified linkedvector
        System.out.println("The new Vector is:"
                           + vector);
    }
}
输出:
Vector:[Geeks, for, Geeks, 10, 20]
Geeks replaced with GFG
The new Vector is:[Geeks, for, GFG, 10, 20]

示例 2:演示 ArrayIndexOutOfBoundsException

// Java code to illustrate setElementAt()
  
import java.io.*;
import java.util.*;
  
public class VectorDemo {
    public static void main(String args[])
    {
        // Creating an empty Vector
        Vector vector
            = new Vector();
  
        // Use add() method to add elements in the vector
        vector.add("Geeks");
        vector.add("for");
        vector.add("Geeks");
        vector.add("10");
        vector.add("20");
  
        // Displaying the linkedvector
        System.out.println("Vector:"
                           + vector);
  
        // Using setElementAt() method to replace 10th with GFG
        // and the 10th element does not exist
        System.out.println("Trying to replace 10th "
                           + "element with GFG");
  
        try {
            vector.setElementAt("GFG", 10);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}
输出:
Vector:[Geeks, for, Geeks, 10, 20]
Trying to replace 10th element with GFG
java.lang.ArrayIndexOutOfBoundsException: 10 >= 5