當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。