|
The friend upstairs spoke very thoroughly, but I still have some doubts:
1. Equals () compares references to the 8 big wrapper classes and String classes, compared to references. When comparing these 9 classes,
The comparison is not a reference, but a conversion to the corresponding basic type (except String-> char []).
(By the way: Why doesn't StringBuffer override equals ()?)
Here is my understanding:
If equals () is not overridden, the comparison between objects will be based on the memory address ratio, so that any instance of any class is not possible
equals () returns true.
If equals () is overridden, it is compared with its own defined method. At this time, even without overriding hashCode (),
The correct comparison result is obtained, but the hashCode returned at this time is different (the same possibility is very small), if you only want
It ’s not much to do anything else (for fun), at this time hashCode is not important to us, but: as the friend upstairs said: When you want to use a hash data structure to store and retrieve data, all It is operated through hashCode. If the hash code is different, then equal () is not needed. If the hash code is the same, then equals () is better than it. ) Is true, but there will still be two or more references to such objects in the Set (because hashCode is different). Another extreme case:
Rewriting hashCode () but not equals () will cause multiple references to the same instance of the same class to be added to the Set. Instances of different classes may not be added because the hashCode is the same (although the probability is crazy) ).
(By the way: how to calculate the hash code of an object in JAVA, isn't it calculated based on the memory address? The memory address is unique, and why may there be duplicate hash codes?)
Don't know even if I understand? I also ask experts to give pointers to younger brothers.
2. The compare method in the Comparator interface produces a comparator, which has a higher comparison level than compareTo () rewritten in the Comparable interface. Is this correct?
Thanks again! |
|