Java Vector setElementAt()方法及实例

Java Vector setElementAt()方法及实例

Java Vector的 setElementAt() 方法用于将该向量的指定索引处的组件设置为指定对象。该位置的前一个分量被丢弃。索引必须是一个大于或等于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<String> vector
            = new Vector<String>();
  
        // 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<String> vector
            = new Vector<String>();
  
        // 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程