按照hashcode()的定义,他的值是由对象在内存中的地址转换而来的,在下面这个程序中
public class HelloWorld { public static void main(String[] args){
String s1=new String("String");
System.out.println(s1.hashCode());
String s2=s1;
//System.out.println(s1.equals(s2));
System.out.println(s2.hashCode());
s2=new String("String");
System.out.println(s2.hashCode());
}
}按照hashcode()的定义,在给s2新建一个对象后,其hashcode()值应该是变化了的,可我得出的结果却与前面是相同的,请问是为什么?
public class HelloWorld { public static void main(String[] args){
String s1=new String("String");
System.out.println(s1.hashCode());
String s2=s1;
//System.out.println(s1.equals(s2));
System.out.println(s2.hashCode());
s2=new String("String");
System.out.println(s2.hashCode());
}
}按照hashcode()的定义,在给s2新建一个对象后,其hashcode()值应该是变化了的,可我得出的结果却与前面是相同的,请问是为什么?
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count; for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}