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


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。