首页 > 解决方案 > 当两个引用变量引用具有相同 hashCode 的同一个对象时,== 返回 false [toString()] 背后的逻辑是什么?

问题描述

==当两个引用变量引用具有相同哈希码值的同一个对象时,返回 false背后的逻辑是什么?

public class One {  
    public static void main(String[] args) {        
        One o = new One();
        One o1 = o; 
        System.out.println(o.toString());                                       
        System.out.println(o1.toString());                                      
        System.out.println(o.hashCode());                                       
        System.out.println(o1.hashCode());                                      
        
        // Why does it print false ?
        System.out.println(o.toString()==o1.toString());    // false                    
        System.out.println(o.hashCode()==o1.hashCode());    // true                 
        System.out.println(o.equals(o1));                   // true
                            
        System.out.println(o.toString().hashCode()==o.toString().hashCode());   // true 
    }
}

标签: javaequalstostringhashcodeobject-class

解决方案


该行与

System.out.println(o.toString()==o1.toString());    // false  

有一个toString()。每个都toString()创建一个新的字符串对象,它们是具有自己内存位置的不同对象。所以==实际上检查了这些新字符串对象之间的内存地址。

始终将字符串与 进行比较String#equals,而不是与进行比较==


推荐阅读