堆棧類的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<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 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<Integer> stack
= new Stack<Integer>();
// 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]
相關用法
- Java Stack get()用法及代碼示例
- Java Stack contains()用法及代碼示例
- Java Stack set()用法及代碼示例
- Java Stack pop()用法及代碼示例
- Java Stack indexOf()用法及代碼示例
- Java Stack containsAll()用法及代碼示例
- Java Stack subList()用法及代碼示例
- Java Stack empty()用法及代碼示例
- Java Stack toArray()用法及代碼示例
- Java Stack setSize()用法及代碼示例
- Java Stack insertElementAt()用法及代碼示例
- Java Stack copyInto()用法及代碼示例
- Java Stack removeElementAt()用法及代碼示例
- Java Stack clear()用法及代碼示例
- Java Stack remove(int)用法及代碼示例
注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack addElement(E) method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。