The picture above is the description in "Alibaba Java Development Manual v1.2.0". Here is a counterexample, saying that the equality situation is not handled, but I think:
o1.getId() > o2.getId()
Isn’t the other way around
o1.getId() <= o2.getId()
I usually use it like this. Could you please help me explain the technique of this place? what is the reason?
给我你的怀抱2017-05-27 17:42:39
After further understanding, the root cause of the problem is that the sorting implementation of JDK7 has been changed to TimSort. See this article for details.
http://blog.2baxb.me/archives...
When I first answered, I didn’t fully understand the author’s intention in asking the question, so I answered a bit hastily. I apologize for that.
The content of the previous answer is divided offline. Because there is a discussion with @wanghaa on the old answer in the answer comments, it is retained. Thank you @wanghaa for making me aware of the problem.
public static void main(String[] args) {
int i = 1;
int j = 1;
int ret = i > j ? 1 : -1;
System.out.println(ret);
}
The above code will output -1. If the two values compared are equal, 0 should be returned. Returning -1 is definitely wrong, so the equal situation must be handled separately.
世界只因有你2017-05-27 17:42:39
After @gemoji’s discussion, I finally understand. To summarize:
In versions before JDK7, just like what is said in Effective Java, Comparator is not mandatory to implement equals.
In versions after JDK7, TimSort is used for sorting. Algorithm, resulting in Comparator must implement equal to.
<<Effective Java Chinese Version>> There is a detailed explanation in it. In fact, this is a strong suggestion. Counterexamples actually destroy the transitivity
and symmetry of equals and comparison