天天看點

Java中Comparator、Comparable總結

 一、對于Comparator的 public int compare(T lhs, T rhs) 通常用在排序中 @return an integer < 0 if {@code lhs} is less than {@code rhs}, 0 if they are equal,    and > 0 if {@code lhs} is greater than {@code rhs}. 對于compare(a, b) 如果小于0,a<b 如果等于0,a=b 如果大于0,a>b

二、對于Comparable中的int compareTo(T another) Comparable一般用于某個容器類中,用于實作compareTo方法 @return a negative integer if this instance is less than {@code another};   a positive integer if this instance is greater than {@code another};   0 if this instance has the same order as {@code another}. 對于a.compareTo(b) 如果小于0,a<b 如果等于0,a=b 如果大于0,a>b

三、關于排序中,Comparetor的使用的說明 Arrays.sort(strs, new Comparator<String>() { public int compare(String s1 ,String s2) { return s1.compareTo(s2); } }); 傳回值大于0的話,s1将排在s2的後面   s2 ....s1 傳回值小于0的話,s1将排在s2的前面   s1 ....s2 傳回值等于0的話,s1将排在s2的位置不變 

四、例如下面的最大堆、最小堆問題

/**
     * 資料流中的中位數
     * 這題的實作方法有很多
     * 未排序的數組(類似快排,根據下标找出中位數)、排好序的數組、排序連結清單、二叉搜尋樹、AVL樹
     * 最小、最大堆是相對時間效率比較高且較容易實作的(java中可以用PriorityQueue來描述最小堆、最大堆)
     * @param num
     */
    PriorityQueue<Integer> maxHeap = new PriorityQueue<Integer>(100, new Comparator<Integer>() {
    	public int compare(Integer o1, Integer o2) {
					return o2.compareTo(o1);
				};
			});
	PriorityQueue<Integer> minHeap = new PriorityQueue<Integer>();
	int insertCount = 0;

	public void Insert(Integer num) {
		insertCount++;
		if (insertCount % 2 == 1) {
			if (!maxHeap.isEmpty() && num < maxHeap.peek()) {
				maxHeap.offer(num);
				num = maxHeap.poll();
			}
			minHeap.offer(num);
		} else {
			if (!minHeap.isEmpty() && num > minHeap.peek()) {
				minHeap.offer(num);
				num = minHeap.poll();
			}
			maxHeap.offer(num);
		}
	}

    public Double GetMedian()throws Exception {
        if (minHeap.isEmpty()) {
			throw new Exception("No numbers are available");
		}
        if (insertCount % 2 == 1) {
			return Double.valueOf(minHeap.peek());
		}else {
			return Double.valueOf(minHeap.peek() + maxHeap.peek()) / 2;
		}   
    }