0

Would appreciate some advice, I have create an array of months that I have to sort in order of length using a comparator. I have created two classes the array list and the comparator but it is not returning them in the correct order as May should be the first month that displays and I don't know where I have gone wrong, posting my code below if anyone can tell me what I have done and how to avoid in the future!. Thanks so much!!

import java.util.*;

public class Q3 implements Comparator.java {
//creating array of months to be sorted in order of length
public int compare(String x, String y) {
    if (x == null)
        return y==null ? 0 : -1;
    else if (y == null)
        return +1;
    else {
        int lenx = x.length();
        int leny = y.length();
        if (lenx == leny)
            return x.compareTo(y);
        else
            return lenx > leny ? -1 : +1;
    }
}

    public static void main(String[] args) {
    String[] data = {
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",

    };
    Arrays.sort(data);
    System.out.println(Arrays.toString(data));
}

}

1 Answers1

2

You should pass the comparator.

Arrays.sort(data, new Q3());
Alex
  • 11,451
  • 6
  • 37
  • 52
  • It looks like `Q3` will sort longest to shortest though. So the last comparison needs to be switched. – erickson Apr 16 '14 at 05:31