首页 > java 中两个 String 具有相同的 hashCode 使用 == 判断返回 false ?

java 中两个 String 具有相同的 hashCode 使用 == 判断返回 false ?

    String str1 = new String("hello");
    String str2 = new String("hello");
        
    System.out.println(str1 == str2);
    System.out.println(str1.equals(str2));
    System.out.println(str1.hashCode());
    System.out.println(str2.hashCode());

代码如上,输出结果:

    false
    true
    99162322
    99162322

为什么具有相同的 hashCode 返回的是 false


看书的时候不仔细,弄清楚了;
String 重写了 hashCode 方法,其 hashCode 值是由内容决定的,而不是地址决定的


  1. hashCode 和 == 是不一样的。 ==比较的是内存地址, 而hashCode是根据实例变量计算出来的。

  2. 你使用了new创建了两个String实例(new 关键字是会开辟新内存空间的),而不是直接引用string池中的“hello”,下面是此构造器的源代码。

    public String(String original) {
       this.value = original.value;
       this.hash = original.hash;
    }

    而String的hash计算方法是根据上述代码中的value和hash。


==比较的是内存地址,hash和equals差不多都是从字符串的每个char得来的,每个char一样,hash一样,但是内存地址不一样


在java中判断String 使用 == 是判断两个对象的地址而不是hashCode。因为你这是两个 String 对象 ,因为你这两个都是使用new 的,所以使用 == 是 false。

【热门文章】
【热门文章】