Home  >  Q&A  >  body text

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

高洛峰高洛峰2713 days ago505

reply all(5)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:08:30

    I was not careful while reading and figured it out;
    String 重写了 hashCode 方法,其 hashCodeThe value is determined by the content, not the address

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:08:30

    Using == to determine String in java is to determine the addresses of two objects instead of hashCode. Because you have two String objects, and because you use new for both of them, using == is false.

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:08:30

    1. hashCode and == are different. == compares memory addresses, and hashCode is calculated based on instance variables.

    2. You used new to create two String instances (the new keyword will open up new memory space), instead of directly referencing "hello" in the string pool. The following is the source code of this constructor.

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

      The hash calculation method of String is based on the value and hash in the above code.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:08:30

    == What is compared is the memory address. Hash and equals are almost obtained from each char of the string. Each char is the same and the hash is the same, but the memory address is different

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:08:30

    == determines whether two reference variables point to the same object. When the contents of two objects are the same, their hashcodes are the same, but their references are not equal

    reply
    0
  • Cancelreply