El método java.util.Stack.contains() se usa para verificar si un elemento específico está presente en la pila o no. Básicamente, se usa para verificar si una pila contiene algún elemento en particular o no.
Sintaxis:
Stack.contains(Object element)
Parámetros: Este método toma un elemento de parámetro obligatorio que es del tipo de Pila. Este es el elemento que debe probarse si está presente en la pila o no.
Valor de retorno: este método devuelve True si el elemento está presente en la pila; de lo contrario, devuelve False .
Los siguientes programas ilustran el método Java.util.Stack.contains():
Programa 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")); } }
Producción:
Stack: [Welcome, To, Geeks, 4, Geeks] Does the Stack contains 'Geeks'? true Does the Stack contains '4'? true Does the Stack contains 'No'? false
Programa 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")); } }
Producción:
Stack: [10, 15, 30, 20, 5] Does the Stack contains 'Geeks'? false Does the Stack contains '4'? false Does the Stack contains 'No'? false