Alibaba Java Development Manual——Comparator
PHPz
PHPz 2017-05-27 17:40:39
0
3
862

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?

PHPz
PHPz

学习是最好的投资!

reply all(3)
给我你的怀抱

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.

黄舟

It should be judged when it is equal to 0

世界只因有你

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!