compareTo
是实例方法,只能对象调用。所以不能比较基本类型
public int compareTo(参数类型 值) {
...
}
参数类型可以是一个 Byte, Double, Integer, Float, Long 或 Short 类型的参数。也可以是String类型
案例:
Long long1 = 1l;
Long long2 = 2l;
Long long3 = 1l;
Long long4 = 4l;
System.out.println(long1.compareTo(long2));//-1
System.out.println(long1.compareTo(long3));//0
System.out.println(long4.compareTo(long1));//1
案例:
String abc = "abc";
String abcde = "abcde";
String one = "1";
String two = "2";
String one2 = "1";
System.out.println(abc.compareTo(abcde));//有一方完全相等,返回字符串长度差-2
System.out.println(one.compareTo(two));//字符不相等,返回ASCII码差值-1
System.out.println(one.compareTo(one2));//字符完全相等,返回0