java int stack_Java Stack remove(int)用法及代码示例

本文详细介绍了Java中的Stack类的remove(int index)方法,该方法用于根据索引从堆栈中删除元素。通过示例代码展示了如何使用此方法并输出删除前后堆栈的状态。示例包括了从不同位置移除元素的情况。
摘要由CSDN通过智能技术生成

Java.util.Stack.remove(int index)方法用于从特定位置或索引中从Stack中删除元素。

用法:

Stack.remove(int index)

参数:此方法接受整数数据类型的强制参数索引,并指定要从堆栈中删除的元素的位置。

返回值:此方法返回刚刚从堆栈中删除的元素。

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

示例1:

// Java code to illustrate remove() when position of

// element is passed as parameter

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");

// Output the Stack

System.out.println("Stack: " + stack);

// Remove the element using remove()

String rem_ele = stack.remove(4);

// Print the removed element

System.out.println("Removed element: "

+ rem_ele);

// Print the final Stack

System.out.println("Final Stack: "

+ stack);

}

}

输出:

Stack: [Geeks, for, Geeks, 10, 20]

Removed element: 20

Final Stack: [Geeks, for, Geeks, 10]

示例2:

// Java code to illustrate remove() when position of

// element is passed as parameter

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(10);

stack.add(20);

stack.add(30);

stack.add(40);

stack.add(50);

// Output the Stack

System.out.println("Stack: " + stack);

// Remove the element using remove()

int rem_ele = stack.remove(0);

// Print the removed element

System.out.println("Removed element: "

+ rem_ele);

// Print the final Stack

System.out.println("Final Stack: "

+ stack);

}

}

输出:

Stack: [10, 20, 30, 40, 50]

Removed element: 10

Final Stack: [20, 30, 40, 50]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值