Java Stack addAll(Collection)方法及示例

Java Stack addAll(Collection)方法及示例

Stack类的addAll(Collection)方法用于将作为该函数参数传递的集合中的所有元素追加到堆栈的末尾,同时牢记集合的迭代器的返回顺序。

语法

boolean addAll(Collection C)

参数: 该方法接受一个强制参数C,它是一个ArrayList的集合。它是一个集合,其元素需要被追加到堆栈的末端。

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

下面的程序说明了Java.util.Stack.addAll()方法。

// Java code to illustrate boolean addAll()
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");
  
        // A collection is created
        Collection<String> c = new ArrayList<String>();
        c.add("A");
        c.add("Computer");
        c.add("Portal");
        c.add("for");
        c.add("Geeks");
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack);
  
        // Appending the collection to the Stack
        stack.addAll(c);
  
        // 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, A, Computer, Portal, for, Geeks]

例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);
  
        // A collection is created
        Collection<Integer> c = new ArrayList<Integer>();
        c.add(1);
        c.add(2);
        c.add(3);
  
        // Displaying the Stack
        System.out.println("The Stack is: " + stack);
  
        // Appending the collection to the Stack
        stack.addAll(c);
  
        // 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, 1, 2, 3]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程