📜  Java中的 PriorityQueue contains() 方法

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

Java中的 PriorityQueue contains() 方法

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

句法:

Priority_Queue.contains(Object element)

参数:参数元素是PriorityQueue的类型。这是需要测试的元素是否存在于队列中。

返回值:如果元素存在于队列中,则该方法返回True ,否则返回 False。

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

// Java code to illustrate contains()
import java.util.PriorityQueue;
  
public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue queue = new PriorityQueue();
  
        // Use add() method to add elements into the Queue
        queue.add("Welcome");
        queue.add("To");
        queue.add("Geeks");
        queue.add("4");
        queue.add("Geeks");
  
        // Displaying the PriorityQueue
        System.out.println("PriorityQueue: " + queue);
  
        // Check for "Geeks" in the queue
        System.out.println("Does the Queue contains 'Geeks'? "
        +queue.contains("Geeks"));
  
        // Check for "4" in the queue
        System.out.println("Does the Queue contains '4'? "
        +queue.contains("4"));
  
        // Check if the Queue contains "No"
        System.out.println("Does the Queue contains 'No'? "
        +queue.contains("No"));
    }
}
输出:
PriorityQueue: [4, Geeks, To, Welcome, Geeks]
Does the Queue contains 'Geeks'? true
Does the Queue contains '4'? true
Does the Queue contains 'No'? false

方案二:

// Java code to illustrate contains()
import java.util.*;
  
public class PriorityQueueDemo {
    public static void main(String args[])
    {
        // Creating an empty PriorityQueue
        PriorityQueue queue = new PriorityQueue();
  
        // Use add() method to add elements into the Queue
        queue.add(10);
        queue.add(15);
        queue.add(30);
        queue.add(20);
        queue.add(5);
  
        // Displaying the PriorityQueue
        System.out.println("PriorityQueue: " + queue);
  
        // Check for '15' in the queue
        System.out.println("Does the Queue contains '15'? "
        +queue.contains(15));
  
        // Check for '2' in the queue
        System.out.println("Does the Queue contains '2'? "
        +queue.contains(2));
  
        // Check if the Queue contains '10'
        System.out.println("Does the Queue contains '10'? "
        +queue.contains(10));
    }
}
输出:
PriorityQueue: [5, 10, 30, 20, 15]
Does the Queue contains '15'? true
Does the Queue contains '2'? false
Does the Queue contains '10'? true