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;
		}   
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值