zoukankan      html  css  js  c++  java
  • compareto方法

    Comparable接口中的compareto方法:

     public int compareTo(T o);

    返回值含义

    小于零:此实例按排序顺序在 obj 前面。

    零:此实例与 obj 在排序顺序中出现的位置相同。

    大于零:此实例按排序顺序在 obj 后面。

    String类中的compareto方法:

    public int compareTo(String anotherString) {
        int len1 = count;
        int len2 = anotherString.count;
        //获取到两个字符串的较短的长度
        int n = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = offset;
        int j = anotherString.offset;
        if (i == j) {
            int k = i;
            int lim = n + i;
            while (k < lim) {
                char c1 = v1[k];
                char c2 = v2[k];
                //如果两个字符的ASC不相同,则直接返回
         if (c1 != c2) {
                    return c1 - c2;
                }
                k++;
            }
        } else {
            while (n-- != 0) { //长度不同的情况:将前面长度相同的字母进行比较,如果不同返回ASCII码的差值;如果都相同,直接求长度的差值
               char c1 = v1[i++];
               char c2 = v2[j++];
                 //如果两个字符的ASC不相同,则直接返回
               if (c1 != c2) {
                   return c1 - c2;
               }
            }
        }
        //如果都一样,返回两个字符串的长度查
        return len1 - len2;
        }

    "abcd".compareTo("adef")== -2

    "abc".compareTo("abcdef")== -3

    "abc".compareTo("abc") == 0

    重写Comparable接口compareto方法

    @Override
    public int compareTo(Object o){
        if(o instanceof Student){
            Student s = (Student)o;
            //return this.name.compareTo(s.name);//按name属性从低到高排序
            return this.id - s.id; //按id属性从小到大排序
        }
        return 0;
    }
  • 相关阅读:
    【Gym
    [matlab工具箱] 曲线拟合Curve Fitting
    数学建模 常用
    “这么多人给我作证,我不怕”
    超星尔雅刷课辅助
    细思《都挺好》
    P5173 传球
    [ICPC 北京 2017 J题]HihoCoder 1636 Pangu and Stones
    CF 1131C Birthday
    CF 634A Island Puzzle
  • 原文地址:https://www.cnblogs.com/yjtm53/p/4149260.html
Copyright © 2011-2022 走看看