views:

68

answers:

3

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  A: 

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;

        }
    }
org.life.java
What if `title.compareTo(o.title) == 0`, `position < o.position` and `order > o.order`. Your method will return `0`.
Sheldon L. Cooper
@Sheldon L. Cooper Thanks I missed that scenario updated the code
org.life.java
+1  A: 

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;
}
Sheldon L. Cooper
Thanks, I will accept this answer since it was the most readable
Shervin
@Shervin you should also consider the quality :-)
org.life.java
And correctness, e.g. avoiding the possibility of overflow. ;-)
Sheldon L. Cooper
A: 

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;
}
matiasg
What if the position or order is a negative value? What happens then? I think then your order of position and order will be reversed
Shervin
Nope, this should give you the same answer as @Sheldon's. The only problem I can see is an overflow here, if, say, position is close to 2^31 (2 to the power 31) and o.position is close to -2^31. But if position and order values range, for instance, from -2^30 to 2^30, then this is ok.
matiasg