string equals int 的有关问题

string equals int 的问题
昨天写程序遇到的一个问题。
public class TestEquals {
/**
* @param args
*/
public static void main(String[] args) {
String s = "1";
Integer i = new Integer(1);
System.out.println(s.equals(1));//false
System.out.println(s.equals(String.valueOf(1))); //true
System.out.println(s.equals(i)); //false
System.out.println(s.equals(i.toString())); //true
}
}




可能没有人会像我这么2 ,去拿string equals int 。。。

equals的参数是Object,java1.6自动封箱 int->Integer 这么写编译的时候也没报错

s.equals(1) 先把 int 1 封箱为 Integer 1 然后比较



jdk中 equals的实现方式

public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}


用string equals int 的时候 在
只有参数是String类型的时候才会比较字符,不是的话比较引用后直接返回