PriorityQueue的compare函數介紹

       優先級隊列是不同於先進先出隊列的另一種隊列。每次從隊列中取出的是具有最高優先權的元素。PriorityQueue是從JDK1.5開始提供的新的數據結構接口。如果不提供Comparator的話,優先隊列中元素默認按自然順序排列,也就是數字默認是小的在隊列頭,字符串則按字典序排列。
在這裏我先羅列一組程序對比一下:

import java.util.*;
public class TestPriorityQueue{
	public static void main(String[] args){
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>(5,new Comparator<Integer>(){
			@Override
			public int compare(Integer o1, Integer o2) {
				if(o2 > o1){
					return 1;
				}
				else if(o2 < o1){
					return -1;
				}
				else {
					return 0;
				}
			}			
		});		
		pq.offer(6);
		pq.offer(-3);
		pq.offer(9);
		pq.offer(0);
		pq.offer(9);
		System.out.println(pq);
		while(!pq.isEmpty()) {
			System.out.print(pq.poll()+",");
		}

		}
	}

結果如下:
[9, 9, 6, -3, 0]
9,9,6,0,-3,

分析爲什麼pq輸出是 [9, 9, 6, -3, 0],原因是pq是按照對象添加到堆中的順序來的。爲什麼會這樣,我現在畫一個示意圖:



這裏爲什麼按照大堆的順序來的,這是否按照什麼來排序,需要看我們重載的compare函數。

其實默認情況下是按照最小堆來排序的,下面 介紹一種不重載compare函數的情況:

import java.util.*;
public class TestPriorityQueue{
	public static void main(String[] args){
		PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
		pq.offer(6);
		pq.offer(-3);
		pq.offer(9);
		pq.offer(0);
		pq.offer(9);
		System.out.println(pq);
		while(!pq.isEmpty()) {
			System.out.print(pq.poll()+",");
		}

		}
	}
結果如下:
[-3, 0, 9, 6, 9]
-3,0,6,9,9,





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章