Java Stack setElementAt()方法与实例

Java Stack setElementAt()方法与实例

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

语法

public void setElementAt(E element, int index)

参数: 这个函数接受两个参数,如上面的语法所示,并描述如下。

  • element : 这是一个新的元素,现有的元素将被替换,与堆栈的对象类型相同。
  • index : 这是一个整数类型的参数,指的是要被替换的元素在堆栈中的位置。

返回值: 该方法不返回任何东西。

异常情况。如果索引超出了范围(index = size()),该方法会抛出ArrayIndexOutOfBoundsException。

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

例1:

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

输出:

Stack:[Geeks, for, Geeks, 10, 20]
Geeks replaced with GFG
The new Stack is:[Geeks, for, GFG, 10, 20]

例2:演示ArrayIndexOutOfBoundsException

// Java code to illustrate setElementAt()
  
import java.io.*;
import java.util.*;
  
public class StackDemo {
    public static void main(String args[])
    {
        // Creating an empty Stack
        Stack<String> stack
            = new Stack<String>();
  
        // Use add() method to add elements in the stack
        stack.add("Geeks");
        stack.add("for");
        stack.add("Geeks");
        stack.add("10");
        stack.add("20");
  
        // Displaying the linkedstack
        System.out.println("Stack:"
                           + stack);
  
        // 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 {
            stack.setElementAt("GFG", 10);
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}

输出:

Stack:[Geeks, for, Geeks, 10, 20]
Trying to replace 10th element with GFG
java.lang.ArrayIndexOutOfBoundsException: 10 >= 5

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程