java stack add push_Java Stack push()用法及代码示例

Java.util.Stack.push(E element)方法用于将元素压入堆栈。元素被推入堆栈的顶部。

用法:

STACK.push(E element)

参数:该方法接受一个类型为Stack的参数element ,表示要压入堆栈的元素。

返回值:该方法返回传递的参数。

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

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

// Java code to illustrate push() method

import java.util.*;

public class StackDemo {

public static void main(String args[])

{

// Creating an empty Stack

Stack STACK = new Stack();

// Use push() to add elements into the Stack

STACK.push("Welcome");

STACK.push("To");

STACK.push("Geeks");

STACK.push("For");

STACK.push("Geeks");

// Displaying the Stack

System.out.println("Initial Stack: " + STACK);

// Pushing elements into the stack

STACK.push("Hello");

STACK.push("World");

// Displaying the final Stack

System.out.println("Final Stack: " + STACK);

}

}

输出:

Initial Stack: [Welcome, To, Geeks, For, Geeks]

Final Stack: [Welcome, To, Geeks, For, Geeks, Hello, World]

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

// Java code to illustrate push() method

import java.util.*;

public class StackDemo {

public static void main(String args[])

{

// Creating an empty Stack

Stack STACK = new Stack();

// Use push() to add elements into the Stack

STACK.push(10);

STACK.push(15);

STACK.push(30);

STACK.push(20);

STACK.push(5);

// Displaying the Stack

System.out.println("Initial Stack: " + STACK);

// Pushing elements into the Stack

STACK.push(1254);

STACK.push(4521);

// Displaying the final Stack

System.out.println("Final Stack: " + STACK);

}

}

输出:

Initial Stack: [10, 15, 30, 20, 5]

Final Stack: [10, 15, 30, 20, 5, 1254, 4521]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值