Java Comparator

Java Comparator,第1张

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 {
  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 {
  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 tm = new TreeMap(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() {
          public int compare(int[] a, int[] b) {
            int aStart, bStart;
            aStart = a[0];
            bStart = b[0];

            return aStart-bStart;
          }
        });

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5687090.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存