import java.io.*;class Test
{
public static void main(String[] args)
{
int i = 4;
int j = 4;
System.out.println(i == j);
// System.out.println(i.compareTo(j)); Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b);
// System.out.println(a.compareTo(b)); String x = "6";
String y = "6";
System.out.println(x == y);
// System.out.println(x.compareTo(y));
}
}
程序的结果是
true
false
true
{
public static void main(String[] args)
{
int i = 4;
int j = 4;
System.out.println(i == j);
// System.out.println(i.compareTo(j)); Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b);
// System.out.println(a.compareTo(b)); String x = "6";
String y = "6";
System.out.println(x == y);
// System.out.println(x.compareTo(y));
}
}
程序的结果是
true
false
true
public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
这个是java.lang.Integer中的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];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
} else {
while (n-- != 0) {
char c1 = v1[i++];
char c2 = v2[j++];
if (c1 != c2) {
return c1 - c2;
}
}
}
return len1 - len2;
}
这个是java.lang.String中的,看了源代码后楼主应该明白输出结果为什么都是0了
== 来比较 int, float, double基本数据类型比较对象时则用compareTo
另外java不能重载运算符有一个例外就是=
compare To比较的是比较引用的对象是否相同