-1

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

}

2
  • 3
    That code wouldn't even compile. Commented Apr 16, 2014 at 5:25
  • And you're not using the comparator. Commented Apr 16, 2014 at 5:28

1 Answer 1

2

You should pass the comparator.

Arrays.sort(data, new Q3());
Sign up to request clarification or add additional context in comments.

1 Comment

It looks like Q3 will sort longest to shortest though. So the last comparison needs to be switched.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.