Java Stack add(Object)方法与实例

Java Stack add(Object)方法与实例

Stack类的add(Object)方法将指定的元素追加到这个Stack的结尾。

语法

boolean add(Object element)

参数: 该函数接受一个单一的参数元素,如上述语法所示。由该参数指定的元素将被追加到堆栈的末尾。

返回值: 该方法成功执行后返回True,否则返回False。

下面的程序说明了java.util.Stack.add(Object element)方法的工作。

例1:

// 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<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");
  
        // Output the present Stack
        System.out.println("The Stack is: "
                           + stack);
  
        // Adding new elements to the end
        stack.add("Last");
        stack.add("Element");
  
        // Printing the new Stack
        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, Last, Element]

例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);
  
        // Output the present Stack
        System.out.println("The Stack is: "
                           + stack);
  
        // Adding new elements to the end
        stack.add(100);
        stack.add(200);
  
        // Printing the new Stack
        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, 200]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程