1. Why should I rewrite the Equals method?
Because the equal method of object is a reference comparison of two objects by default, it means pointing to the same memory, the address being equal, otherwise unequal; If you now need to use the values of the fields inside the object to determine equality, override the Equals method.
2, why rewrite the Hashcode method?
The general place does not need to rewrite the hashcode, only when the class needs to put in Hashtable, HashMap, HashSet and so on hash structure's collection to rewrite the hashcode, then why overloads the Hashcode? For HashMap, like HashMap is a large memory block, there are a lot of small memory block, small memory block inside is a series of objects, you can use Hashcode to find small memory block Hashcode%size (small number of memory blocks), so when equals equal, The hashcode must be equal, and if it is an object, you must override the Hashcode and equal methods.
3, why equals () equal, hashcode must be equal, and hashcode equal, but does not require equals equal?
1, because the small memory block is accessed according to Hashcode, the hashcode must be equal.
2. HashMap gets an object that compares key hashcode equals and equals to true.
The reason why hashcode equal, but can be unequal, such as objecta and OBJECTB they all have attribute name, then hashcode all in name, so hashcode, but two objects belong to different types, So equals is false.
4, why need Hashcode?
1, through the hashcode can quickly find small memory block.
2, through hashcode comparison than Equals method faster, when get first compare hashcode, if hashcode different, directly return false.
The "Java Foundation" overrides the Equals () method while overriding the Hashcode () method