class MyClass{ int x; MyClass(int i) { x = i; } public static void main(String args[]) { MyClass m1 = new MyClass(100); MyClass m2 = new MyClass(100); if(m1.equals(m2)) { System.out.println("Both are equal"); } else { System.out.println("Both are not equal"); } } }为什么
输出是:Both are not equal而不是 Both are equal ?
输出是:Both are not equal而不是 Both are equal ?
但在内存的不同位置上
因为MyClass m1 = new MyClass(100);
和 MyClass m2 = new MyClass(100);
分别用 new 产生的MyClass的两个对象,所以 if(m1.equals(m2)) 的结果是false
它就调用Object类的equals的方法,而这个方法是根据Object类的hashCode方法
来判断,在Object类中hashCode方法返回的是对象的地址,
所以你的结果总是不相等
顶个
String s1="abc";
String s2="abc";
hashCode()相等
所以它只是调用Object中的equals()方法代码如下:
public boolean equals(Object obj) {
return (this == obj);
}
可以发现这个方法是用来比较两个引用是否指向同一个对象的,所以会返回false而String中重写了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;
}
而这样是相等的
public class MyClass{ int x; MyClass(int i) { x = i; } public static void main(String args[]) {
String s1=new String("a");
String s2=new String("a"); if (s1.equals(s2)) { System.out.println("Both are equal"); } else { System.out.println("Both are not equal"); } }}
对于String型比较的是内容是否相同