當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java PriorityQueue contains()用法及代碼示例


Java.util.PriorityQueue.contains()方法用於檢查PriorityQueue中是否存在特定元素。因此,本質上,它用於檢查隊列是否包含任何特定元素。

用法:

Priority_Queue.contains(Object element)

參數:參數element 是PriorityQueue的類型。如果隊列中是否存在此元素,則需要對其進行測試。


返回值:如果該元素存在於隊列中,則該方法返回True,否則返回False。

以下示例程序旨在說明Java.util.PriorityQueue.contains()方法:
示例1:

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

示例2:

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


相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 PriorityQueue contains() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。