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

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

public interface Comparable<T> {
    /**
     * @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).

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,780评论 18 399
  • 关于 Swift 重要这个文档所包含的准备信息, 是关于开发的 API 和技术的。这个信息可能会改变, 根据这个文...
    无沣阅读 4,392评论 1 27
  • 转自:http://blog.csdn.net/jackfrued/article/details/4492194...
    王帅199207阅读 8,628评论 3 93
  • 今天第一次跟宝儿玩儿拼图,第一次拼……拼的是熊宝宝一家。欢儿边上专心的看着,边看变动边念叨:熊爸爸、熊妈妈,大熊宝...
    欢欢乐乐1317阅读 224评论 0 0
  • 以为闭上双眼就能迎接每一个天明, 以为离开苦难就能期待每一次幸福, 以为关上心门就能假装每一天都在, 以为放下过往...
    3e1dcc93e441阅读 449评论 0 0