>  기사  >  Java  >  Java의 PriorityQueue

Java의 PriorityQueue

PHPz
PHPz원래의
2024-08-30 16:04:30596검색

일반적으로 대기열의 개체는 FIFO 순서로 배치됩니다. 즉, 선입선출(First In First Out)입니다. 어떤 경우에는 우선순위에 따라 객체를 처리해야 하는데 이때 Java PriorityQueue가 작동하게 됩니다. 그 외에도 PriorityQueue에는 다음과 같은 특정 기능이 있습니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

  • 무제한 대기열입니다.
  • 기본적으로 요소의 순서는 자연스러운 순서입니다.
  • Null 값은 허용되지 않습니다.
  • 비교 불가능한 객체는 PriorityQueue 생성에 사용할 수 없습니다.

Java PriorityQueue 선언

Java PriorityQueue는 아래 구문을 사용하여 선언할 수 있습니다.

public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable

Java PriorityQueue 생성자

다음은 Java PriorityQueue에서 일반적으로 사용되는 생성자입니다.

1. PriorityQueue(): PriorityQueue는 초기 용량이 기본값이므로 11로 생성됩니다. 게다가, 요소들은 자연스러운 순서에 따라 정렬됩니다.

2. PriorityQueue(CollectionE> c): PriorityQueue는 다음과 같습니다. 언급된 컬렉션의 요소로 제작되었습니다.

3. PriorityQueue(int ic): PriorityQueue는 언급된 초기 용량 IC로 생성됩니다. 게다가, 요소들은 자연스러운 순서에 따라 정렬됩니다.

4. PriorityQueue(int ic, Comparator< super E> comparator): PriorityQueue는 언급된 초기 용량 IC로 생성됩니다. 또한, 언급된 비교자를 기준으로 요소의 순서가 지정됩니다.

5. PriorityQueue(PriorityQueueE> c): PriorityQueue는 다음과 같습니다. 언급된 PriorityQueue의 요소로 생성되었습니다.

6. PriorityQueue(SortedSetE> c): PriorityQueue는 언급된 정렬 세트의 요소로 생성됩니다.

방법

이제 Java PriorityQueue에서 일반적으로 사용되는 몇 가지 메소드를 살펴보겠습니다.

1. add(E e): 이 메소드를 호출하면 요소 e가 PriorityQueue에 추가됩니다.

2. size(): 컬렉션의 요소 개수가 반환됩니다.

3. clear(): PriorityQueue의 모든 요소가 제거됩니다.

4. 비교기(): 큐를 정렬하는 데 사용되는 비교기가 반환됩니다. 자연순서를 사용하면 null이 반환됩니다.

5. 포함(객체o): 큐에 언급된 요소 o가 포함되어 있으면 true가 반환됩니다.

6. iterator(): 대기열의 요소에 사용되는 반복자가 반환됩니다.

7. Offer(Ee): 언급된 요소 e가 대기열에 삽입됩니다.

8. peek(): PriorityQueue의 헤드는 제거되지 않고 검색됩니다. 요소가 없는 경우 null이 반환됩니다.

9. poll(): PriorityQueue의 헤드가 검색되고 제거됩니다. 요소가 없는 경우 null이 반환됩니다.

10. 제거(객체o): 언급된 요소의 단일 인스턴스가 대기열에서 제거됩니다.

11. toArray(): 큐에 있는 모든 요소의 배열이 반환됩니다.

12. toArray(T[] a): 큐에 있는 모든 요소의 배열이 반환되며 런타임은 언급된 배열과 같습니다.

Java PriorityQueue의 예

아래는 Java PriorityQueue의 예입니다.

예시 #1

PriorityQueue를 생성하는 샘플 프로그램.

코드:

import java.util.Iterator;
import java.util.PriorityQueue;
class Main{
public static void main(String args[]){
//create a PriorityQueue
PriorityQueue<String> q=new PriorityQueue<String>();
//add elements to the queue
q.add("Anna");
q.add("Annamu");
q.add("Adam");
q.add("Iza");
q.add("Thukidi");
System.out.println("Head of the queue:"+q.element());
System.out.println("Head of the queue :"+q.peek());
//Retrieve elements in queue using iterator
System.out.println("Queue elements are :");
Iterator it=q.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
//remove the element from queue
q.remove();
//remove the head of the queue
q.poll();
System.out.println("\n Queue after the removal of 2 elements :");
//Retrieve elements in queue using iterator
Iterator<String> it2=q.iterator();
while(it2.hasNext())
{
System.out.println(it2.next());
}
}
}

출력:

Java의 PriorityQueue

샘플 프로그램 작업:

  • 우선순위 대기열 생성 q.
  • 대기열에 요소를 추가합니다.
  • 대기열의 선두를 인쇄하세요.
  • 반복자를 사용하여 대기열의 모든 요소를 ​​인쇄합니다.
  • 두 요소를 제거하세요.
  • 두 요소를 제거한 후 대기열의 모든 요소를 ​​인쇄합니다.

예시 #2

비교기를 사용하여 PriorityQueue를 생성하는 샘플 프로그램

Code:

import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
class PriorityQueueExample{
public static void main(String[] args) {
//Create a custom comparator. In this, length of 2 strings are getting compared
Comparator<String> cmp = new Comparator<String>()
{
@Override
public int compare(String str1, String str2) {
return str1.length() - str2.length();
}
};
// PriorityQueue creation with Comparator
PriorityQueue<String> q = new PriorityQueue<>(cmp);
// Add elements to the Queue
q.add("Anna");
q.add("Annamu");
q.add("Adam");
q.add("Iza");
q.add("Thukidi");
q.add("Sam");
q.add("Elsa");
q.add("Kukku");
q.add("Mathu");
q.add("Radha");
// Remove elements from the Queue
while (!q.isEmpty()) {
System.ou<em>t</em>.println(q.remove());
}
}
}

Output:

Java의 PriorityQueue

Working of the sample program:

  • Create a custom comparator where the elements in the Queue are compared based on the length.
  • Create a PriorityQueue q.
  • Add elements to the Queue.
  • Remove the elements from the queue based on the length of the strings.
  • Print the elements in the queue in the order of removal.

Example #3

Sample program to implement a PriorityQueue by making use of different methods.

Code:

import java.util.*;
class Main{
public static void main(String args[]){
//create a PriorityQueue
PriorityQueue<String> q=new PriorityQueue<String>();
//add elements to the queue
q.add("Anna");
q.add("Annamu");
q.add("Adam");
q.add("Iza");
q.add("Thukidi");
System.out.println("Head of the queue:"+q.element());
System.out.println("Head of the queue :"+q.peek());
//Retrieve elements in queue using iterator
System.out.println("Queue elements are :");
Iterator it=q.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
//remove the element from queue
q.remove();
//remove the head of the queue
q.poll();
// Check whether the element Anna is present in queue using the method Contains()
boolean b = q.contains("Anna");
System.out.println("Is there any element Anna in the PriorityQueue ? " + b);
//Check whether the element Iza is present in queue using the method Contains()
boolean bl = q.contains("Iza");
System.out.println("Is there any element Anna in the PriorityQueue ? " + bl);
}
}

Output:

Java의 PriorityQueue

Working of the sample program:

  • Create a PriorityQueue q.
  • Add elements and Print the head of the queue.
  • Print all the elements in the Queue using iterator.
  • Remove two elements using the methods remove() and poll().
  • Check whether the two elements Anna and Iza are available in Queue using the method Contains().

위 내용은 Java의 PriorityQueue의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.