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

Java.util.Stack.insertElementAt(element,index)方法用于在Stack的指定索引处插入特定元素。元素和位置都作为参数传递。如果在指定的索引处插入元素,则所有元素都被向上推一,因此容量增加,从而为新元素创建了空间。

用法:

Stack.insertElementAt()

参数:该方法接受两个参数:

  • element:这是需要插入堆栈中的元素。
  • index:这是整数类型,是指要插入新元素的位置。

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

异常:如果索引是无效数字,则此方法将引发ArrayIndexOutOfBoundsException。

以下示例程序旨在说明Java.util.Stack.insertElementAt()方法:

示例1:将String元素添加到Stack中。

// Java code to illustrate insertElementAt() 
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 into the Stack 
        stack.add("Welcome"); 
        stack.add("To"); 
        stack.add("Geeks"); 
        stack.add("4"); 
        stack.add("Geeks"); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Inseting element at 3rd position 
        stack.insertElementAt("Hello", 2); 
  
        // Inseting element at last position 
        stack.insertElementAt("World", 6); 
  
        // Displaying the final Stack 
        System.out.println("The final Stack is "
                           + stack); 
    } 
}

输出:

Stack: [Welcome, To, Geeks, 4, Geeks]
The final Stack is [Welcome, To, Hello, Geeks, 4, Geeks, World]

示例2:将Integer元素添加到堆栈中。

// Java code to illustrate insertElementAt() 
import java.util.*; 
  
public class StackDemo { 
    public static void main(String args[]) 
    { 
        // Creating an empty Stack 
        Stack<Integer> stack = new Stack<Integer>(); 
  
        // Use add() method to add elements into the Stack 
        stack.add(10); 
        stack.add(20); 
        stack.add(30); 
        stack.add(40); 
        stack.add(50); 
  
        // Displaying the Stack 
        System.out.println("Stack: " + stack); 
  
        // Inseting element at 1st position 
        stack.insertElementAt(100, 0); 
  
        // Inseting element at fifth position 
        stack.insertElementAt(200, 4); 
  
        // Displaying the final Stack 
        System.out.println("The final Stack is "
                           + stack); 
    } 
}

输出:

Stack: [10, 20, 30, 40, 50]
The final Stack is [100, 10, 20, 30, 200, 40, 50]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学如逆水行舟,不进则退3038

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值