简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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