compare function

Comparator: static class MyCompare implements Comparator {

          // descending order

        public int compare(Integer one, Integer two) {

              if(one<two)

                    return 1;

              if(one>two)

                    return -1;

              return 0;

        }

  }

If your Comparator's compare(T o1, T o2) return a negative when o1 is less than o2, you get ascending order.

If your Comparator's compare(T o1, T o2) return a negative when o1 is greater than o2, you get descending order.

CompareTo: return a negative number if our object comes before the one passed in; -1 表明 从小到大 return a positive number if our object comes after the one passed in; +1 表明 从大到小 otherwise, zero (meaning they're equal in terms of ordering).

在JDK库中,有一部分类实现了Comparable接口,有个compareTo(object o)方法.对于表达式x.compareTo(y),如果返回值大于0 ,表示x>y;如果返回值小于0,表示x<y;如果返回值等于0,表示x=y.

TreeSet: 默认升序排序。用降序排列的比较函数时,得到降序。 PriorityQueue: 默认最小堆。用降序排列的比较函数初始化,是最大堆。

results matching ""

    No results matching ""