栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java Comparator

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/686545.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号