当前位置:网站首页>Equals method

Equals method

2022-07-07 20:00:00 Whiteye too white

“==” And equals The difference between

“==” For basic types , Compare values ; For reference types, the address is compared .

Object Class equals The default implementation of is equivalent to “==”, That is, compare the addresses of reference types .

Java There are many classes in the library ( Such as String、Date、Long、HashMap and File Class etc. ) It's all rewritten Object Class equals Method , Lead to its and “==” Unequivalence .

String Overridden in class equals First “==” Compare the reference addresses of two reference types , Same returns true, Compare the strings with different reference addresses .

rewrite equals Method must override hashCode Method

hashCode One of the things that methods actually have to do is , For the sake of equals Method returns the same hash value for the same object .

Object Class equals Method to distinguish two objects by comparing the address value , That is to use “==”. And if we rewrite it according to business needs equals Method implementation , Then it should also be rewritten at the same time hashCode Method implementation . otherwise hashCode Method still returns the basis Object Class based on address value integer Hash value .

原网站

版权声明
本文为[Whiteye too white]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071749177500.html

随机推荐