且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

java中==,equals和hashcode的示例

更新时间:2022-06-24 07:43:10

== 确实比较了对象(我的意思是 - 两个引用都指向同一个对象),而不是它们的内容,而 .equal 比较内容(至少对于String)。

== does compare real equality of objects (I mean - both references point to the same object), not their content, whereas .equal compares content (at least for String).

String a = new String("aa");
String b = new String("aa"); 

a b 指向不同的对象。

还要注意,如果对象相等,那么它们的hashchodes必须相同,但如果hashcode是相同的,这并不意味着对象是平等的。

Notice also that if objects are equal then their hashchodes must be the same, but if hashcodes are the same, it doesn't mean that objects are equal.