java string 的地址:为什么s1与s3的哈希值相等

benbencan 2017-03-24 11:12:45
以下程序的运行结果:
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忽略大小写内容不同");
}

}
...全文
278 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
liu_siat 2017-03-24
  • 打赏
  • 举报
回复
s1和s3内容相同,存储在内存的不同区域。 s1可以理解放在一个字符串常量池中
李德胜1995 2017-03-24
  • 打赏
  • 举报
回复

value都是常量池中的JAVA。。。所以hashCode()方法结果相同
zs808 2017-03-24
  • 打赏
  • 举报
回复
对于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值也会遵守上述的原则。

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧