나는 설명서와 내가 PriorityQueue에 대해 알 수있는 모든 것을 읽었지만 여전히 출력이 왜 이상한 지 알지 못한다. 나는 명령 추가의 요령을 얻을 수 없다는 것을 의미한다.
Java의 PriorityQueue에서이 이상한 순서가 발생하는 이유는 무엇입니까?
PriorityQueue<String> pq = new PriorityQueue<String>();
pq.offer("2");
System.out.println("add 2 : " + pq);
pq.offer("4");
System.out.println("add 4 : " + pq);
System.out.println(pq.peek() + " ");
pq.offer("1");
System.out.println("offer 1 : " + pq);
pq.offer("3");
System.out.println("add 3 : " + pq);
pq.remove("1");
System.out.println("remove 1 : " + pq);
출력 :
add 2 : [2]
add 4 : [2, 4] <- why 4 goes there
offer 1 : [1, 4, 2] <- why 1 goes first
add 3 : [1, 3, 2, 4] <- why reorder
remove 1 : [2, 3, 4] <- again
요소는 [힙 순서] (https://en.wikipedia.org/wiki/Heap_%28data_structure%29)에 있습니다. –
고려해야 할 점은'PriorityQueue'는'String'에서 값을 정렬하는 것과 같이'toString'을 구현합니다. 'toString'이'AbstractCollection'에 구현되어있는 것처럼 보입니다. 그렇다고해서 그렇지 않을 수도 있습니다. 올바른 순서로 요소를 가져 오려면'poll'을 사용해보십시오. –
@JohnB AbstractCollection의 경우 : "문자열 표현은 콜렉션의 요소 목록이 대괄호 ("[] ")로 묶인 반복기에 의해 반환되는 순서로 구성됩니다." PriorityQueue가 그 메소드 자체를 오버라이드하지 않는다면, 그것이 주문되었다는 보장이 있어야한다. –