博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

hashcode and equals

Posted on 2014-03-12 20:53  钟悍  阅读(189)  评论(0编辑  收藏  举报

About hashcode and equals

Rule 1:

   If override equals(), and should override hashcode(), make sure if two object 'equals', then them should have same hashcode.

   actual, you also break the rule, the compile will pass, but it maybe cause some bugs.

Rule 2:

   If two object not equals, then they hashcode can be the same or not.

 

So:

1,  If two objects 'equals', them must have some hashcode.

2,  If two objects 'not equals', them maybe have some hashcode.

3,  If two objcts have same hashcode, they maybe 'not equals'

4,  If two objects have different hashcode, they must 'not equals'

 

If hashmap, it check hashcode first and then check equals.