String a="a";
String b=new String("a");
String c=new String("a");
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
执行的结果是 :
97
97
97 我的理解 b c的hashCode 不应该相等啊. 因为 b c在堆内存里各创建了两个对象.只是加入了对"a"常量字符的引用而已.
String b=new String("a");
String c=new String("a");
System.out.println(a.hashCode());
System.out.println(b.hashCode());
System.out.println(c.hashCode());
执行的结果是 :
97
97
97 我的理解 b c的hashCode 不应该相等啊. 因为 b c在堆内存里各创建了两个对象.只是加入了对"a"常量字符的引用而已.
而String由于其本身的不可改变这种特性,所以比较的时候是‘==’来判断的
所以,你这个程序之中,他们的hashcode相等,只能说明他们之间相互equals,即:b.equals(c)是true
但是,b == c 却是false
多看下equals和==的区别,再查查String的API吧。
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;
}
用==,equals,hashcode什么都是一样的。
相反的 int 型以小写字母开头, 它只是简单的数据类型.new String的话会调用 这个类的构造函器.
但如果是"=="它看得是内存地址 因为a,b,c 是不同的对象 所以"==" 为false