Java中Comparator、Comparable总结

来源:互联网 发布:dfa算法 编辑:程序博客网 时间:2024/06/11 16:26

一、对于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