📌  相关文章
📜  Java中的 Stack containsAll() 方法与示例

📅  最后修改于: 2022-05-13 01:54:46.637000             🧑  作者: Mango

Java中的 Stack containsAll() 方法与示例

Java StackcontainsAll()方法用于检查两个堆栈是否包含相同的元素。它将一个堆栈作为参数,如果此堆栈的所有元素都存在于另一个堆栈中,则返回 True。

句法:

public boolean containsAll(Collection C)

参数:参数C是一个集合。该参数是指需要在此堆栈中检查其元素出现的堆栈。

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

下面的程序说明了 Stack.containsAll() 方法:

方案一:

// Java code to illustrate
// Stack containsAll()
  
import java.util.*;
  
class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty stack
        Stack
            stack = new Stack();
  
        // 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
            stack2 = new Stack();
  
        // 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

方案二:

// Java code to illustrate boolean containsAll()
  
import java.util.*;
  
class StackDemo {
    public static void main(String args[])
    {
  
        // Creating an empty stack
        Stack
            stack = new Stack();
  
        // 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
            stack2 = new Stack();
  
        // 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