Java Stack contains()方法及实例
java.util.Stack.contains()方法是用来检查一个特定的元素是否存在于堆栈中。因此,基本上它是用来检查一个堆栈是否包含任何特定的元素。
语法
Stack.contains(Object element)
参数: 这个方法需要一个强制性的参数元素,它的类型是Stack。这是需要测试的元素,如果它在Stack中存在或不存在。
返回值: 如果该元素存在于Stack中,该方法返回True,否则返回False。
以下程序说明了Java.util.Stack.contains()方法。
程序1 :
// Java code to illustrate contains()
import java.util.*;
public class StackDemo {
public static void main(String args[])
{
// Creating an empty Stack
Stack<String> stack = new Stack<String>();
// Use add() method to add elements into the Stack
stack.add("Welcome");
stack.add("To");
stack.add("Geeks");
stack.add("4");
stack.add("Geeks");
// Displaying the Stack
System.out.println("Stack: " + stack);
// Check for "Geeks" in the Stack
System.out.println("Does the Stack contains 'Geeks'? "
+ stack.contains("Geeks"));
// Check for "4" in the Stack
System.out.println("Does the Stack contains '4'? "
+ stack.contains("4"));
// Check if the Queue contains "No"
System.out.println("Does the Stack contains 'No'? "
+ stack.contains("No"));
}
}
输出:
Stack: [Welcome, To, Geeks, 4, Geeks]
Does the Stack contains 'Geeks'? true
Does the Stack contains '4'? true
Does the Stack contains 'No'? false
示例2
// Java code to illustrate contains()
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 into the Stack
stack.add(10);
stack.add(15);
stack.add(30);
stack.add(20);
stack.add(5);
// Displaying the Stack
System.out.println("Stack: " + stack);
// Check for "Geeks" in the Stack
System.out.println("Does the Stack contains 'Geeks'? "
+ stack.contains("Geeks"));
// Check for "4" in the Stack
System.out.println("Does the Stack contains '4'? "
+ stack.contains("4"));
// Check if the Stack contains "No"
System.out.println("Does the Stack contains 'No'? "
+ stack.contains("No"));
}
}
输出:
Stack: [10, 15, 30, 20, 5]
Does the Stack contains 'Geeks'? false
Does the Stack contains '4'? false
Does the Stack contains 'No'? false
极客教程