Comparable接口(一)----java内置类

实现Comparable接口下的唯一方法comparaTo()就可以比较类的大小,这些类包括java内置的包装类(Integer类,Character类等)、日期类和自定义的类(当然得自己实现Comparable接口,重写comparaTo方法)。

public interface Comparable {
    /**
     * @param   o the object to be compared.
     * @return  a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
     * @throws NullPointerException if the specified object is null
     * @throws ClassCastException if the specified object's type prevents it from being compared to this object.
     */

    public int compareTo(T o);
}

Integer类的比较,根据基本数据类型比较。

 public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }
 public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

Character类的比较,根据Unicode编码顺序比较。Unicode表中,序号30-39是数字“0,1,2···9”,序号65-90是大写字母“A,B,C···Z”,序号97-122是小写字母“a,b,c···z”。

 public int compareTo(Character anotherCharacter) {
        return compare(this.value, anotherCharacter.value);
    }
 public static int compare(char x, char y) {
        return x - y;
    }

String类的比较。如果一个字符串是另一个起始开始的子串,返回两个字符串的长度差,否则逐个比较字符的Unicode码大小,返回不相等时unicode码之差。

  public int compareTo(String anotherString) {
        int len1 = value.length;
        int len2 = anotherString.value.length;
        int lim = Math.min(len1, len2);
        char v1[] = value;
        char v2[] = anotherString.value;

        int k = 0;
        while (k < lim) {
            char c1 = v1[k];
            char c2 = v2[k];
            if (c1 != c2) {
                return c1 - c2;
            }
            k++;
        }
        return len1 - len2;
    }

例如abc和aBc比较,返回b和B的Unicode码之差32(98-66).

你可能感兴趣的:(Comparable接口(一)----java内置类)