priority 사용방법큐?
가 정렬할 대상을 정렬하려면 어떻게 해야 합니까?
또, 와 방법은 다른가요?
합니다.이 오버로드가 합니다.Comparator<? super E> comparator
정렬 순서에 따라 적절한 방법으로 비교한 비교기를 전달합니다. 꽤 입니다. (단순히
곳에서 바와 :offer
★★★★★★★★★★★★★★★★★」add
는 다른 인터페이스 방식의 실장일 뿐입니다. 있는에는 JDK가 .add
®offer
.~하다add
★★★★★★★★★★★★★★★★★」offer
능력에 의해 일반적으로 다른 행동을 할 가능성이 있다offer
크기 제한으로 인해 값을 추가할 수 없음을 나타내기 위해 이 차이는 다음과 같습니다.PriorityQueue
한없이 넓어느니.
다음으로 priority 큐를 문자열 길이로 정렬하는 예를 나타냅니다.
// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
Comparator<String> comparator = new StringLengthComparator();
PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}
// StringLengthComparator.java
import java.util.Comparator;
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() - y.length(),
// which would be more efficient.
if (x.length() < y.length()) {
return -1;
}
if (x.length() > y.length()) {
return 1;
}
return 0;
}
}
출력은 다음과 같습니다.
짧다
중간의
참으로 오래도록
Java 8 솔루션
하면 됩니다.lambda expression
★★★★★★★★★★★★★★★★★」method reference
Java 8 서 java java java java java java java java java java java 。 값이 5가 String 를 할 수 .Priority String은 String ( capacity 5 )는 String ( String ) 。
람다 식 사용
PriorityQueue<String> pq=
new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());
메서드 참조 사용
PriorityQueue<String> pq=
new PriorityQueue<String>(5, Comparator.comparing(String::length));
다음 중 하나를 사용할 수 있습니다.
public static void main(String[] args) {
PriorityQueue<String> pq=
new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
// or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
pq.add("Apple");
pq.add("PineApple");
pq.add("Custard Apple");
while (pq.size() != 0)
{
System.out.println(pq.remove());
}
}
인쇄:
Apple
PineApple
Custard Apple
큐로 하기 위해) 하거나 "priority" ("priority")를 합니다.reversed
같이요.
PriorityQueue<String> pq = new PriorityQueue<String>(5,
Comparator.comparing(String::length).reversed());
'어느 때 보다'를 사용할 도 있어요.Collections.reverseOrder
:
PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5,
Collections.reverseOrder(Comparator.comparing(String::length))
'이렇게 하다'라는 것을 알 수 .Collections.reverseOrder
커스텀 오브젝트에 도움이 될 수 있는 비교기를 사용하기 위해 오버로드되었습니다.reversed
는 ''를 사용합니다.Collections.reverseOrder
:
default Comparator<T> reversed() {
return Collections.reverseOrder(this);
}
오퍼() vs add()
문서에 따라
오퍼 메서드는 가능한 경우 요소를 삽입하고 그렇지 않으면 false를 반환합니다.이는 선택되지 않은 예외를 발생시키는 것만으로 요소를 추가하지 못할 수 있는 Collection.add 메서드와 다릅니다.오퍼 방식은 고정용량(또는 "바운딩" 큐 등)에서 예외적인 문제가 아닌 일반적인 장애일 때 사용하도록 설계되었습니다.
capacity-restricted 큐를 사용할 때는 add()보다 oper()가 일반적으로 권장됩니다.add()는 예외를 발생시키는 것만으로 요소를 삽입할 수 없습니다.우선 순위큐는 priority 힙에 기반한 무제한 priority 큐입니다.
적절한 것을 컨스트럭터에게 전달해 주세요.
PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
와의 유일한 차이점은 이들이 속한 인터페이스입니다. offer
에 속해 있습니다.add
는, 최초로 인터페이스에 표시됩니다.두 가지 방법 모두 동일한 작업을 수행합니다. 즉, 지정된 요소를 priority 큐에 삽입합니다.
Queue API에서:
오퍼 메서드는 가능한 경우 요소를 삽입하고 그렇지 않으면 false를 반환합니다.이는 선택되지 않은 예외를 발생시키는 것만으로 요소를 추가하지 못할 수 있는 Collection.add 메서드와 다릅니다.오퍼 방식은 고정용량(또는 "바운딩" 큐 등)에서 예외적인 문제가 아닌 일반적인 장애일 때 사용하도록 설계되었습니다.
javadoc에서 선언한 바와 같이 다르지 않습니다.
public boolean add(E e) {
return offer(e);
}
번 건네다Comparator
in . .신 . . . . . . . . . . . 。T
람다 사용(Java 8+):
int initialCapacity = 10;
PriorityQueue<T> pq = new PriorityQueue<>(initialCapacity, (e1, e2) -> { return e1.compareTo(e2); });
익명의 클래스를 사용하는 일반적인 방법:
int initialCapacity = 10;
PriorityQueue<T> pq = new PriorityQueue<>(initialCapacity, new Comparator<T> () {
@Override
public int compare(T e1, T e2) {
return e1.compareTo(e2);
}
});
역순으로 정렬하려면 e1, e2를 바꿉니다.
만 하면 됩니다.add()
»offer()
되어 있고은 그렇지 않을 수 질문(question(질문)
인터페이스 큐의 JavaDoc에 따르면 "Offer 메서드는 가능한 경우 요소를 삽입하고 그렇지 않으면 false를 반환합니다.이는 선택되지 않은 예외를 발생시키는 것만으로 요소를 추가하지 못할 수 있는 Collection.add 메서드와 다릅니다.오퍼 방식은 고정 용량(또는 "바운딩" 큐 등)에서 예외적으로 발생하는 것이 아니라 일반적인 장애일 때 사용하도록 설계되었습니다.
, 해야 함)를할 수 있는 , "(Priority)"는 "Priority"는 "Priority"는 "Priority"는 "Priority"는 "Priority"는 "Priority"는 "Priority"는 "Priority"는 "Priority"를 의미합니다.큐)는 동일하게 동작합니다.이 수 없는 에는 이 요소를 추가할 수 없습니다.offer()
해드리겠습니다.false
add()
코드에는 원하지 않는 불쾌한 체크되지 않은 예외를 발생시킵니다.했을 경우, 의미 는, 「」를 사용해 .offer()
것을 한다면 .을 합니다.add()
Collection 인터페이스의 사양에 따라 발생하는 예외를 처리합니다.
두 '보다'를 위해 됩니다.offer()
에 false
(캐퍼시티 제한 큐에서 권장되는 방식) 및 Collection 인터페이스 상의 계약을 유지합니다.Collection 인터페이스에서는 항상 예외가 발생하여 실패합니다.
어쨌든, 적어도 질문의 그 부분이 명확해졌으면 좋겠네요.
여기서는 사용자 정의 비교기를 정의할 수 있습니다.
아래 코드:
import java.util.*;
import java.util.Collections;
import java.util.Comparator;
class Checker implements Comparator<String>
{
public int compare(String str1, String str2)
{
if (str1.length() < str2.length()) return -1;
else return 1;
}
}
class Main
{
public static void main(String args[])
{
PriorityQueue<String> queue=new PriorityQueue<String>(5, new Checker());
queue.add("india");
queue.add("bangladesh");
queue.add("pakistan");
while (queue.size() != 0)
{
System.out.printf("%s\n",queue.remove());
}
}
}
출력:
india pakistan bangladesh
오퍼 메서드와 추가 메서드의 차이: 링크
를 사용하는 대신 사용하는 클래스를 사용할 수도 있습니다.PriorityQueue
구현(및 그에 따라 오버라이드)compareTo
★★★★★★★★★★★★★★★★★★」
의: 반 use use use use use use use use use use use use use 만 사용하는 좋습니다.Comparable
Comparator
순서가 - 하기 위한 사용 - if if if if if if if if if if if if if if if if if if if if if if if if if if if if if if if if if if if 。Person
은 그냥 게 것 요.Comparator
★★★★★★ 。
import java.lang.Comparable;
import java.util.PriorityQueue;
class Test
{
public static void main(String[] args)
{
PriorityQueue<MyClass> queue = new PriorityQueue<MyClass>();
queue.add(new MyClass(2, "short"));
queue.add(new MyClass(2, "very long indeed"));
queue.add(new MyClass(1, "medium"));
queue.add(new MyClass(1, "very long indeed"));
queue.add(new MyClass(2, "medium"));
queue.add(new MyClass(1, "short"));
while (queue.size() != 0)
System.out.println(queue.remove());
}
}
class MyClass implements Comparable<MyClass>
{
int sortFirst;
String sortByLength;
public MyClass(int sortFirst, String sortByLength)
{
this.sortFirst = sortFirst;
this.sortByLength = sortByLength;
}
@Override
public int compareTo(MyClass other)
{
if (sortFirst != other.sortFirst)
return Integer.compare(sortFirst, other.sortFirst);
else
return Integer.compare(sortByLength.length(), other.sortByLength.length());
}
public String toString()
{
return sortFirst + ", " + sortByLength;
}
}
출력:
1, short
1, medium
1, very long indeed
2, short
2, medium
2, very long indeed
프린트 오더도 궁금했어요.예를 들어 다음과 같은 경우를 생각할 수 있습니다.
priority 큐의 경우:
PriorityQueue<String> pq3 = new PriorityQueue<String>();
다음 코드:
pq3.offer("a");
pq3.offer("A");
인쇄 방법은 다음과 같습니다.
String[] sa = {"a", "A"};
for(String s : sa)
pq3.offer(s);
다른 포럼 토론에서 답을 찾았습니다.사용자는 "offer()/add() 메서드는 요소만 큐에 삽입합니다.예측 가능한 순서를 원할 경우 큐의 헤드를 반환하는 peek/poll을 사용해야 합니다."
priority 큐에는 각 요소에 할당된 priority가 있으며 priority가 가장 높은 요소가 큐의 맨 위에 표시됩니다.각 요소에 우선순위를 할당하는 방법은 사용자에게 달려 있습니다.그렇지 않으면 Java는 기본 방식으로 작업을 수행합니다.값이 가장 작은 요소가 가장 높은 우선순위로 할당되므로 먼저 큐에서 삭제됩니다.우선순위가 가장 높은 요소가 여러 개 있는 경우 동점이 임의로 발생합니다.생성자에서 비교기를 사용하여 순서를 지정할 수도 있습니다. PriorityQueue(initialCapacity, comparator)
코드 예:
PriorityQueue<String> queue1 = new PriorityQueue<>();
queue1.offer("Oklahoma");
queue1.offer("Indiana");
queue1.offer("Georgia");
queue1.offer("Texas");
System.out.println("Priority queue using Comparable:");
while (queue1.size() > 0) {
System.out.print(queue1.remove() + " ");
}
PriorityQueue<String> queue2 = new PriorityQueue(4, Collections.reverseOrder());
queue2.offer("Oklahoma");
queue2.offer("Indiana");
queue2.offer("Georgia");
queue2.offer("Texas");
System.out.println("\nPriority queue using Comparator:");
while (queue2.size() > 0) {
System.out.print(queue2.remove() + " ");
}
출력:
Priority queue using Comparable:
Georgia Indiana Oklahoma Texas
Priority queue using Comparator:
Texas Oklahoma Indiana Georgia
또는 커스텀 컴퍼레이터를 정의할 수도 있습니다.
import java.util.Comparator;
public class StringLengthComparator implements Comparator<String>
{
@Override
public int compare(String x, String y)
{
//Your Own Logic
}
}
초기 학습에 사용할 수 있는 간단한 예를 다음에 나타냅니다.
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
public class PQExample {
public static void main(String[] args) {
//PriorityQueue with Comparator
Queue<Customer> cpq = new PriorityQueue<>(7, idComp);
addToQueue(cpq);
pollFromQueue(cpq);
}
public static Comparator<Customer> idComp = new Comparator<Customer>(){
@Override
public int compare(Customer o1, Customer o2) {
return (int) (o1.getId() - o2.getId());
}
};
//utility method to add random data to Queue
private static void addToQueue(Queue<Customer> cq){
Random rand = new Random();
for(int i=0;i<7;i++){
int id = rand.nextInt(100);
cq.add(new Customer(id, "KV"+id));
}
}
private static void pollFromQueue(Queue<Customer> cq){
while(true){
Customer c = cq.poll();
if(c == null) break;
System.out.println("Customer Polled : "+c.getId() + " "+ c.getName());
}
}
}
언급URL : https://stackoverflow.com/questions/683041/how-do-i-use-a-priorityqueue
'programing' 카테고리의 다른 글
Vuex: 작업이 완료될 때까지 기다리는 방법 (0) | 2022.08.07 |
---|---|
Vue-cli를 사용하여 CSS를 "dist/vue-COMPONT_NAME.js" 파일에 빌드할 수 있습니까? (0) | 2022.08.07 |
Clang이 초과 부동소수점 정밀도에 어떻게 대처하는지 설명하는 문서가 있습니까? (0) | 2022.08.07 |
vuex에서 nuxt-i18n 패키지의 localRoute를 사용하는 방법 (0) | 2022.08.03 |
Visual Studio C/C++ 콘솔 응용 프로그램에서 콘솔 창 닫힘 방지 (0) | 2022.08.03 |