Is this a correct way of sorting by title, position and then order by using a Comparator?

六月ゝ 毕业季﹏ 提交于 2019-12-13 02:56:57

问题


Consider this class.

public class DynamicField implements Comparable<DynamicField> {
    String title;
    int position;
    int order;

    @Override
    public int compareTo(DynamicField o) {
        if(position < o.position) 
            return -1;
        if(position > o.position)
            return 1;

        if(order < o.order)
            return -1;
        if(order > o.order)
            return 1;

        return title.compareTo(o.title);

    }
}

Is the compareTo method correct if I want to sort by title, position and then order?


回答1:


No, you're making comparisons in an incorrect order. Rearranging comparisons order would make it work:

@Override
public int compareTo(DynamicField o) {
    int c = title.compareTo(o.title);
    if (c != 0)
      return c;
    if(position < o.position) 
        return -1;
    if(position > o.position)
        return 1;
    if(order < o.order)
        return -1;
    if(order > o.order)
        return 1;
    return 0;
}



回答2:


No,Try this code Updated

  public class DynamicField implements Comparable<DynamicField> {
        String title;
        int position;
        int order;

        @Override
        public int compareTo(DynamicField o) {
            int result = title.compareTo(o.title);
            if(result != 0) {}             
            else if(position != o.position)
                result = position-o.position;
            else if(order != o.order)
                result = order- o.order;

            return result;

        }
    }



回答3:


This is actually the same as @org.life.java's answer. You might find this one more palatable, though.

@Override
public int compareTo() {
    int result = title.compareTo(o.title);
    if (result == 0)
        result = position - o.position;
    if (result == 0)
        result = order - o.order;
    return result;
}


来源:https://stackoverflow.com/questions/3823608/is-this-a-correct-way-of-sorting-by-title-position-and-then-order-by-using-a-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!