其实什么都不需要讲的、说的!!!
应为Object中的equals是比较的内存地址。
如果一个类没有重写equals方法,那么就继承Object中的那个equals方法。
在JAVA中==与equals的差别:
大家都知道==比较的都是内存地址值。
下面主要讲解equals:
在Object类中定义了方法:
public boolean equals(Object obj) {
return (this == obj);
}
大家这时候有人认为equals和==没有区别了。都是比较的内存地址。
但是在String中又定义了方法:
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;
}
这个方法不仅比较地址,而且比较内容。此时的equals比较的就是两个对象地址值与内容。
一般我们开发的时候都是覆写equals方法!
String str1="abc";//此时相当于new了一个String对象
String str2="abc";//此时相当于new了一个String对象
但是:
str1==str2---->>>>true
因为String中有个类似缓冲池,先有个"abc"在内存中,然后如果有其他的String 对象的时候首先来这里找有没有相同的。
如果有就使用缓冲池中的