The difference and connection of Hashcode and equals methods in JAVA

From: https://blog.csdn.net/SongYuxinIT/article/details/81911645

The difference between hashCode and equals methods:

1. Two objects with equal () equal must have equal hashCode (), that is, using equal () to compare is absolutely reliable.

2. Two objects whose hashCode () is equal, their equal () is not necessarily equal, that is, hashCode () is not absolutely reliable.

 因为重写的equal()里一般比较的比较全面比较复杂,这样效率就比较低,而利用hashCode()进行对比,则只要生成一个hash值进行比较就可以了,效率很高,那么hashCode()既然效率这么高为什么还要equal()呢?

 因为hashCode()并不是完全可靠,有时候不同的对象他们生成的hashcode也会一样(生成hash值得公式可能存在的问题),所以hashCode()只能说是大部分时候可靠,并不是绝对可靠。

Solution:

 当需要对比的时候,首先用hashCode()去对比,如果hashCode()不一样,则表示这两个对象肯定不相等(也就是不必再用equal()去再对比了),如果hashCode()相同,此时再对比他们的equal(),如果equal()也相同,则表示这两个对象是真的相同了,这样既能大大提高了效率也保证了对比的绝对正确性。

Original link: https://blog.csdn.net/SongYuxinIT/article/details/81911645

Published 8 original articles · Likes2 · Visits 504

Guess you like

Origin blog.csdn.net/qq_42003546/article/details/98940401