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


Java Stack containsAll()用法及代碼示例


Java Stack的containsAll()方法用於檢查兩個堆棧是否包含相同的元素。它使用一個堆棧作為參數,如果該堆棧的所有元素都存在於另一個堆棧中,則返回True。

用法:

public boolean containsAll(Collection C)

參數:參數C是一個Collection。此參數表示需要在此堆棧中檢查其元素出現情況的堆棧。


返回值:如果此堆棧包含其他堆棧的所有元素,則該方法返回True,否則返回False。

以下示例程序旨在說明Stack.containsAll()方法:

示例1:

// Java code to illustrate 
// Stack containsAll() 
  
import java.util.*; 
  
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"); 
  
        // prints the stack 
        System.out.println("Stack 1: "
                           + stack); 
  
        // Creating another empty stack 
        Stack<String> 
            stack2 = new Stack<String>(); 
  
        // Use add() method to 
        // add elements in the stack 
        stack2.add("Geeks"); 
        stack2.add("for"); 
        stack2.add("Geeks"); 
        stack2.add("10"); 
        stack2.add("20"); 
  
        // prints the stack 
        System.out.println("Stack 2: "
                           + stack2); 
  
        // Check if the stack 
        // contains same elements 
        System.out.println("\nDoes stack 1 contains stack 2: "
                           + stack.containsAll(stack2)); 
    } 
}
輸出:
Stack 1: [Geeks, for, Geeks, 10, 20]
Stack 2: [Geeks, for, Geeks, 10, 20]

Does stack 1 contains stack 2: true

示例2:

// Java code to illustrate boolean containsAll() 
  
import java.util.*; 
  
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"); 
  
        // prints the stack 
        System.out.println("Stack 1: "
                           + stack); 
  
        // Creating another empty stack 
        Stack<String> 
            stack2 = new Stack<String>(); 
  
        // Use add() method to 
        // add elements in the stack 
        stack2.add("10"); 
        stack2.add("20"); 
  
        // prints the stack 
        System.out.println("Stack 2: "
                           + stack2); 
  
        // Check if the stack 
        // contains same elements 
        System.out.println("\nDoes stack 1 contains stack 2: "
                           + stack.containsAll(stack2)); 
    } 
}
輸出:
Stack 1: [Geeks, for, Geeks]
Stack 2: [10, 20]

Does stack 1 contains stack 2: false


相關用法


注:本文由純淨天空篩選整理自Code_r大神的英文原創作品 Stack containsAll() method in Java with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。