当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stack setElementAt()用法及代码示例


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

用法:

public void setElementAt(E element, int index)

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


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

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

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

以下示例程序旨在说明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


相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack setElementAt() method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。