【问题标题】:Why do 2 Object have diff hash codes, but 2 String have the same hash codes in Java?为什么 2 个 Object 具有不同的哈希码,而 2 个 String 在 Java 中具有相同的哈希码?
【发布时间】:2015-05-29 17:48:32
【问题描述】:
class A{
    int a;
    A(){
        this.a = 100;
    }
}
//in main, we have:
A a = new A(), b = new A();
//and
String str0 = "123", str1 = "123";

为什么str0和str1的hash码一样,而a和b不一样?

【问题讨论】:

  • str0 和 str1 指向 StringPool 中的相同引用,而 'a' 和 'b' 指向内存中的不同引用,因为使用了 'new' 关键字。
  • 与String interning无关。
  • @Crazyjavahacking 确实如此。即使String 没有 覆盖hashCode,OP 也会得到相同的结果,因为str1str2 是对同一个对象的引用,而ab不是。
  • 你在混合概念。如果对象相等,hashCode() 必须返回相同的值,就是这样。实习在这里无关紧要,因为无论如何对象都是平等的。
  • @pbabcdef 但它确实覆盖了hashCode,,这使得实习变得无关紧要。

标签: java dictionary hash hashmap


【解决方案1】:

因为String 覆盖 Object.hashCode() 而你的班级没有。

这意味着String 类具有hashCode() 的特定实现,它将根据String 值计算散列。所以对于两个具有相同值的字符串,哈希码会是相同的。

当您创建一个新类A 时,例如,如果您没有为hashCode() 提供您自己的实现,它将使用类Object 的默认实现。默认实现只能保证哈希码来自完全相同的实例

Objects.hash()(用于多个值)和Objects.hashCode()(用于单个值)方法可以更轻松地在您自己的类中实现hashCode()。例如:

class A{
    int a;

    A() {
        this.a = 100;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(a);
    }
}

请注意,如果用于创建哈希的属性值在某个时候发生变化,hashCode() 的结果可能也会发生变化。

【讨论】:

    【解决方案2】:

    因为java.lang.String类中hashCode()的实现被覆盖了。

    为了能够在集合中使用Strings,必须重写实现。

    【讨论】:

      【解决方案3】:

      因为 String 的 hashCode 实现已构建为始终以给定顺序为相同的字符集合返回相同的哈希码。而 Object.hashCode() 将任何对象视为唯一的。如果你想知道两个字符串是否是不同的对象,那么你可以 Objects.hashCode(someString)

      /**
       * 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;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-06-22
        • 2020-03-25
        • 2013-04-30
        • 2015-12-21
        • 1970-01-01
        • 2012-09-24
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多