Java Stack addElement(E)方法与实例

Java Stack addElement(E)方法与实例

Stack类的addElement(E)方法用于将作为参数传递给该函数的元素附加到Stack的末尾。

语法

boolean addElement(E obj)

这里,E是指这个容器所维护的元素的类型 是这个容器所维护的元素类型。

参数: 该函数接受一个参数E obj,它是要添加到堆栈末端的对象。

返回值: 如果至少执行了一个append动作,该方法返回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]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程