当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stack addAll(Collection)用法及代码示例


堆栈类的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]


相关用法


注:本文由纯净天空筛选整理自Code_r大神的英文原创作品 Stack addAll(Collection) method in Java with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。