在自定义创建的比较器中实现compare()方法 [英] Implementation of compare() method in custom created Comparators

查看:461
本文介绍了在自定义创建的比较器中实现compare()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class IntegerComparator implements Comparator< Integer> 
{
@Override
public int compare(Integer o1,Integer o2){
if(o1< o2)
return 1;
else if(o1> o2)
return -1;
else
return 0;
}
}

它给出了降序。我知道。我记得它盲目。我不明白为什么实现必须是这样的。



我希望结果是升序。因为按升序,如果你取任意两个相邻的元素,o1应该总是小于o2。



有人可以揭示其背后的逻辑。



编辑:




  • 当元素被交换时。是比较结果返回1吗?


解决方案

请记住:




  • 返回-1将第一个对象放在第二个对象之前(一般值小于0),


  • 返回1在第二个对象之后放置第一个对象(一般值大于0)。



这是重复所有的对象进行比较,你有一个升序排序。请参阅



在此动画中:




  • a> b - >返回+1(向右移动,b之后)

  • b - > return -1(a b left left,before b)


class IntegerComparator implements Comparator<Integer>
{
@Override
public int compare(Integer o1, Integer o2) {
    if(o1 < o2)
        return 1;
    else if(o1 > o2)
        return -1;
    else
    return 0;
}   
}

It gives the descending order. I know it. I remember it blindly. I dont understand why the implementation has to be like this.

I expect the results to be ascending order. Because in ascending order, the o1 should be always less than o2 if you take any two adjacent elements. But It gives the descending order which I dont expect.

Can someone demystify the logic behind it

Edit:

  • When the elements are swapped. Is it when the compare returns 1 ?

解决方案

Remember that:

  • returning -1 put the first object before the second (generally value less than 0),
  • returning 0 do nothing,
  • returning 1 put the first object after the second (generally value more than 0).

This is repeated over all the object to compare and you have a ascending sorting. See bubble sorting algo on google/youtube.

You can see:

Collections.reverseOrder(myComparator);

To get a new Comparator with a reverse order of yours.

In this animation:

  • a > b -> return +1 (a moving right, after b)
  • a < b -> return -1 (a moving left, before b)

这篇关于在自定义创建的比较器中实现compare()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆