Java中的堆栈 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 stack
= new Stack();
// 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 stack
= new Stack();
// 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