Java Stack containsAll()方法及实例
Java Stack的containsAll()方法是用来检查两个堆栈是否包含相同的元素。它以一个堆栈为参数,如果这个堆栈的所有元素都存在于另一个堆栈中,则返回True。
语法
public boolean containsAll(Collection C)
参数: 参数C是一个集合。这个参数指的是需要在这个堆栈中检查其元素出现的堆栈。
返回值: 如果这个堆栈包含其他堆栈的所有元素,该方法返回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
极客教程