hashcode and equals

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.

原文地址:https://www.cnblogs.com/zhonghan/p/3597289.html