📜  Java中的 Stack contains() 方法和示例

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

Java中的 Stack contains() 方法和示例

Java.util.Stack.contains()方法用于检查特定元素是否存在于堆栈中。所以基本上它用于检查堆栈是否包含任何特定元素。

句法:

Stack.contains(Object element)

参数:此方法采用堆栈类型的强制参数元素。这是需要测试的元素是否存在于堆栈中。

返回值:如果元素存在于堆栈中,则此方法返回True ,否则返回False

下面的程序说明了Java.util.Stack.contains() 方法:

方案一:

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

方案二:

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