以下程序的运行结果:
s1与s3引用的不是同一地址
java.lang.String2269730
java.lang.String2269730
s1的 值与s3相同
s1与s3忽略大小写内容相同
问题:为什么s1与s3的哈希值相等
public class equalsTest { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
           String s1="JAVA";
           String s2=new String("Java");
           String s3=new String("JAVA");
           
           if (s1==s3)  {
            System.out.println("s1与s3引用同一地址");
               System.out.println(s1.getClass().getName() + s1.hashCode());
            System.out.println(s3.getClass().getName() + s3.hashCode());
           }
           else{
            System.out.println("s1与s3引用的不是同一地址");
            System.out.println(s1.getClass().getName() + s1.hashCode());
            System.out.println(s3.getClass().getName() + s3.hashCode());
           }
           if (s1.equals(s3))
            System.out.println("s1的 值与s3相同");
           else
            System.out.println("s1与s3的值不同 ");
           if (s1.equalsIgnoreCase(s3))
            System.out.println("s1与s3忽略大小写内容相同");
           else
            System.out.println("s1与s3忽略大小写内容不同");
}    }

解决方案 »

  1.   

    s1和s3内容相同,存储在内存的不同区域。
    s1可以理解放在一个字符串常量池中
      

  2.   

    对于hash值的计算,是调用hashCode()方法来进行的。lz问题产生的原因,是因为String重写了Object的hashCode()方法,以下是String类的hashCode()方法实现:
        /**
         * Returns a hash code for this string. The hash code for a
         * {@code String} object is computed as
         * <blockquote><pre>
         * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
         * </pre></blockquote>
         * using {@code int} arithmetic, where {@code s[i]} is the
         * <i>i</i>th character of the string, {@code n} is the length of
         * the string, and {@code ^} indicates exponentiation.
         * (The hash value of the empty string is zero.)
         *
         * @return  a hash code value for this object.
         */
        public int hashCode() {
            int h = hash;
            if (h == 0 && value.length > 0) {
                char val[] = value;            for (int i = 0; i < value.length; i++) {
                    h = 31 * h + val[i];
                }
                hash = h;
            }
            return h;
        }可以看到,String的hashCode的计算方法就是将每个字符进行hash * 31 + charAt(i)的方式进行迭代。当然,最终的值会受每个字符的影响啦(大写字母与小写字母的字符值不一样)。hashCode与equals是成对出现的,也就是说,hashCode不同,equals必然不同。但是,hashCode相同,equals也有可能不同。另外,对于没有实现equals的对象,会默认使用Object.equals,该方法是在jvm里实现的,跟对象的内存地址,当前系统状态等等都有关系,同样,这个hashCode值也会遵守上述的原则。
      

  3.   


    value都是常量池中的JAVA所以hashCode()方法结果相同