简体   繁体   English

这是使用比较器按标题,位置然后排序的正确方法吗?

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

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? 如果要按标题,位置然后按顺序排序,compareTo方法是否正确?

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;

        }
    }

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;
}

This is actually the same as @org.life.java's answer. 这实际上与@ org.life.java的答案相同。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM