源代码如下:
public class Fin {
public static void main(String[] args) {
String s1="abc"+"def";
String s2=new String(s1);
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
输出:
-1424385949
-1424385949s1.equals(s2)为true
s1==s2为false谁知道原因啊?
public class Fin {
public static void main(String[] args) {
String s1="abc"+"def";
String s2=new String(s1);
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}
输出:
-1424385949
-1424385949s1.equals(s2)为true
s1==s2为false谁知道原因啊?
equals操作表示的两个变量是否是对同一个对象的引用,即堆中的内容是否相同。
s1和s2内容相同,地址也相同啊
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
很明显String类的hashcode返回的值是根据字符串内容得到的。算法如下:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。(空字符串的哈希值为 0。) 而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;
}
如果比较的是同一对象或者值一样都会返回true.
楼主的疑问就是因为hashcode方法已经被该写而你却一直认为它是返回内存的地址……