java addelement_Java Stack addElement(E)用法及代码示例

堆栈类的addElement(E)方法用于在堆栈末尾将作为参数传递的元素附加到此函数。

用法:

boolean addElement(E obj)

Here, E is the type of elements maintained

by this container.

参数:该函数接受参数E obj,它是要在堆栈末尾添加的对象。

返回值:如果至少执行了一个附加操作,则该方法返回True,否则返回False。

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

示例1:

// Java code to illustrate boolean addElement()

import java.util.*;

import java.util.ArrayList;

public class GFG {

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

// Displaying the Stack

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

// Appending "GeeksForGeeks" to the Stack

stack.addElement("GeeksForGeeks");

// Clearing the Stack using clear() and displaying

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

}

}

输出:

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

The new Stack is: [Geeks, for, Geeks, 10, 20, GeeksForGeeks]

示例2:

// Java code to illustrate

// boolean add(Object element)

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

// Displaying the Stack

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

// Appending 100 to the Stack

stack.addElement(100);

// Clearing the Stack using clear() and displaying

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

}

}

输出:

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

The new Stack is: [10, 20, 30, 40, 50, 100]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值