源代码如下:
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
-1424385949
s1.equals(s2)为true
s1==s2为false
谁知道原因啊?
------解决方案--------------------
==操作比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量在堆中存储的地址是否相同,即栈中的内容是否相同。
equals操作表示的两个变量是否是对同一个对象的引用,即堆中的内容是否相同。
------解决方案--------------------
s1.equals(s2),equals的意思就像是说:s1和s2是不是长得像(比较内容),当然一样啊,true
== 意思是s1和s2是不是同一个人,(比较存储的地址) 当然不一样啦false
------解决方案--------------------
楼主:请注意Object类的hashcode方法是根据对象在内存中的地址返回的。
而String类改写了这个方法。你可以看下String类的源码:
- Java code
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; }