equals和hashCode()

In java, object classes inherit equals Object () and hashCode () method for comparing whether two objects are equal

If you do not rewrite the comparison is the memory address, different objects, the memory address is certainly different,

If two objects are equal according to the need to determine its own logic, then you need to rewrite equals () and hashCode () method

equals and hashCode role is actually the same, are used to compare whether two objects are equal, but why have equals hashCode need it?

Because, equals method is generally more comprehensive complex, are judged by equals, then efficiency is relatively low. And the need to produce hashCode hashCode value comparison value can be a very high efficiency, it can be used hashCode first determination,

But why such a high efficiency hashCode, equals need it?

Because hashCode not necessarily accurate, objects hashCode two values ​​are equal, not equal two objects described, this time need to be determined equals

Whenever the need to compare, first () to contrast with hashCode, if hashCode () is not the same, it means that these two objects is certainly not equal (that is, then you do not have to equal () and then compared to), if hashCode () the same, this time to compare their equal (), if equal () are the same, then the two objects are really the same, and so can greatly improve the efficiency but also to ensure the absolute correctness of the contrast!

in principle:

Equal to 1. equals, then hashCode value must equal (if hashCode values ​​are not equal, that equals a certain range, that is not the same objects)

Equal 2. hashCode, equals not necessarily equal

 

HashSet deposit:

Into the object obj

Obj hashCode calculation of the value, and hashCode value has been placed objects are equal, if not want to wait, certainly illustrate different objects directly into, if they are equal, then equals judge, then placed equal, and so it did not want to give up

 

 

HashMap access operation:

put:

First, the value obtained hashCode, hash algorithm hashCode worth to an array index, find the corresponding position, if null, directly into, if not null, the link address method, equals the method of determining whether a key is present in the list If there is, put the original value of the replacement key, if not, then add

 

Guess you like

Origin www.cnblogs.com/gucl/p/11311792.html