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