java 中两个 String 具有相同的 hashCode 使用 == 判断返回 false ?
高洛峰
高洛峰 2017-04-18 10:06:30
0
5
534
高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(5)
刘奇

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

巴扎黑

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.

巴扎黑
  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.

大家讲道理

== 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

洪涛

== 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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!