A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

请问,图中的compareTo是哪来的?它是哪个类里面的函数?

6 个回复

倒序浏览
调用的String 和Integer 类里面的compareTo方法
回复 使用道具 举报
public interface Comparable<T>此接口强行对实现它的每个类的对象进行整体排序。这种排序被称为类的自然排序,类的 compareTo 方法被称为它的自然比较方法
int compareTo(T o)
          比较此对象与指定对象的顺序。
回复 使用道具 举报
s1.getName()返回的String
s1.getAge()返回的是int

int num=s1.getName().compareTo(s2.getName());
等价于
String name1=s1.getName();
String name2=s2.getName();
int num=name1.comareTo(name2);//这是调用的String的compareTo

return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
等价于
int age1=s1.getAge();
int age2=s2.getAge();
return new Integer(age1).compareTo(newt Integer(age2));//这是调用的Integer的compareTo
回复 使用道具 举报
leon_hm 发表于 2014-4-2 08:42
s1.getName()返回的String
s1.getAge()返回的是int

谢谢,很详细!
回复 使用道具 举报
public interface Comparable<T> {     public int compareTo(T o); }  public final class Integer extends Number implements Comparable<Integer> {     ...     public static int compare(int x, int y) {         return (x < y) ? -1 : ((x == y) ? 0 : 1);     }     ...     public int compareTo(Integer anotherInteger) {         return compare(this.value, anotherInteger.value);     }     ... }
回复 使用道具 举报
public interface Comparable<T> {
    public int compareTo(T o);
}

public final class Integer extends Number implements Comparable<Integer> {
    ...
    public static int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }
    ...
    public int compareTo(Integer anotherInteger) {
        return compare(this.value, anotherInteger.value);
    }
    ...
}
希望你从以上源码看出点compareTo是怎么来的。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马