I have long had doubts about the hashCode and equals methods, and I have never been able to solve them. Today I remember Baidu, But I did write it in my own words, so it should be original.
Values in HashSet or HashMap cannot be repeated. Let's assume that there are already 1000 values in it,
Below I want to save 1,001st values. How can I determine whether these 1001 values are equal to the first 1000 values?
At this time, someone will say that the equals method is used. Yes, yes, but it is not very slow if you want to equals the 1000 values ?, 1000 is okay, so what if it is 10000 or 100000? This is not enough.
So hashCode is used as an address value. When you store data, you can directly find the physical memory corresponding to your hashCode to see if you have already stored a value. If you do not store it, You can store it directly. If you store it, call the equals method, if they are equal, they are discarded, and they are stored together with the form of a bulb.
Therefore, when you create a class and you want to rewrite the equals method, you 'd better also rewrite the hashCode. Otherwise, you have created two attributes and the methods are all equal, can insert HashSet or HashMap, which may be contrary to your original intention.
Another point is that the criteria for judging hashCode and equals should be the same. For example, you use equals to determine whether the two attributes in the object are equal to each other to determine whether the object is equal, the value returned by your hashCode method is also related to the two attributes.
Because your hashCode is used to prevent equals from judging the existence of so many times, there may be other in-depth functions)