源代码如下:
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谁知道原因啊?

解决方案 »

  1.   

    ==操作比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量在堆中存储的地址是否相同,即栈中的内容是否相同。
    equals操作表示的两个变量是否是对同一个对象的引用,即堆中的内容是否相同。
      

  2.   

    那s1==s2为啥是false啊,你别随便复制别人的答案啊,看题啊
    s1和s2内容相同,地址也相同啊
      

  3.   

    s1 s2的内容和地址都相等,为啥s1==s2为false啊,请看题再回答
      

  4.   

    s1.equals(s2),equals的意思就像是说:s1和s2是不是长得像(比较内容),当然一样啊,true== 意思是s1和s2是不是同一个人,(比较存储的地址) 当然不一样啦false
      

  5.   

    楼主:请注意Object类的hashcode方法是根据对象在内存中的地址返回的。而String类改写了这个方法。你可以看下String类的源码:
        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方法已经被该写而你却一直认为它是返回内存的地址……
      

  6.   

    听君一席言,胜读十年书啊,在下佩服佩服,终于知道hashcode原来不是地址了啊