Why should override the hashcode () and equals ()?

Figuratively, a man named Joe Smith who go to the hotel, the front desk complete the registration name went to the 99 floor, 100 room, this time the police arrived to find the front desk called Zhang three people live in this room, after inquiry, the hotel has 50 accommodation called Zhang III, requires traversing query, the query is not convenient.

Then change another way of registration, registration ID number when the front desk and found that there are duplicate ID number when the police arrived to find the reception ID number, the same hashcode value is calculated through the hashing algorithm is then assigned to a room produce linked list query performance is very slow, then when the police find will encounter problems.

You can only change the way the third register, while the registration ID number and name when the front desk, so when the police came to investigate at the same time in accordance with the two conditions so that we can direct people looking to lock in which room.

In the program: good Front Bi Haxi algorithm registration, the name is like comparing equals method, comparing like hashcode method only when the ID number of equals and hashcode are met to ensure that the same object.

When we rewrite the equals method together with a class should override hashcode method, and both methods should be met:

1: Consistency, namely: when two objects equals the comparison is true, then the values ​​should be equal hashcode, and vice versa, because when two objects hashcode values ​​are equal, but equals the comparison is false, then the list will have influence in the HashMap query performance.

2: Paired rewrite that it should rewrite rewrite equals hashcode.

 

Guess you like

Origin www.cnblogs.com/mike-mei/p/11222417.html