Java Comparator

Compare()

int compare(T obj1, T obj2)

  • Compare obj1 to obj2 (obj1 - obj2)
  • Returns zero if obj1 = obj2

  • Returns positive if obj1 > obj2

  • Returns negative if obj1 < obj2

  • ClassCastException if the types of the objects are not compatible

Customize Comparator

By overriding compare()

Basic example:

// A reverse comparator for strings.
class MyComp implements Comparator<String> {
  public int compare(String a, String b) {
    String aStr, bStr;
    aStr = a;
    bStr = b;
    // Reverse the comparison.
    return bStr.compareTo(aStr);
  }
  // No need to override equals.
}
  • Create a custom class implementing Comparator and overrides compare( )

  • String method compareTo( ) compares the two strings

TreeMap example:

// Compare last whole words in two strings.
class TComp implements Comparator<String> {
  public int compare(String a, String b) {
    int i, j, k;
    String aStr, bStr;
    aStr = a;
    bStr = b;
    // Find index of beginning of last name.
    i = aStr.lastIndexOf(' ');
    j = bStr.lastIndexOf(' ');
    k = aStr.substring(i).compareTo(bStr.substring(j));
    if(k==0) // last names match, check entire name
      return aStr.compareTo(bStr);
    else
return k; }
  // No need to override equals.
}

// Create a tree map with the new comparator
    TreeMap<String, Double> tm = new TreeMap<String, Double>(new TComp());

// Insert in the sorted order
    tm.put("John Doe", new Double(3434.34));
    tm.put("Tom Smith", new Double(123.22));
    tm.put("Jane Baker", new Double(1378.00));
    tm.put("Tod Hall", new Double(99.22));
    tm.put("Ralph Smith", new Double(-19.08));
  • TComp compares two strings that hold first and last names.

  • This yields a tree map that is sorted by last name, and within last name by first name.

Array.sort example:


        // intervals: int[][], where intervals[i] = [starti, endi]
        // sort the intervals by starti
        Arrays.sort(intervals, new Comparator<int[]>() {
          public int compare(int[] a, int[] b) {
            int aStart, bStart;
            aStart = a[0];
            bStart = b[0];

            return aStart-bStart;
          }
        });

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值