Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

}

share|improve this question

closed as off-topic by chrylis, Jayan, laalto, Felix Yan, Mark Apr 16 '14 at 12:37

This question appears to be off-topic. The users who voted to close gave these specific reasons:

  • "This question was caused by a problem that can no longer be reproduced or a simple typographical error. While similar questions may be on-topic here, this one was resolved in a manner unlikely to help future readers. This can often be avoided by identifying and closely inspecting the shortest program necessary to reproduce the problem before posting." – Jayan, Mark
  • "This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself." – chrylis, laalto, Felix Yan
If this question can be reworded to fit the rules in the help center, please edit the question.

3  
That code wouldn't even compile. –  Rohit Jain Apr 16 '14 at 5:25
    
And you're not using the comparator. –  Pietu1998 Apr 16 '14 at 5:28

1 Answer 1

You should pass the comparator.

Arrays.sort(data, new Q3());
share|improve this answer
    
It looks like Q3 will sort longest to shortest though. So the last comparison needs to be switched. –  erickson Apr 16 '14 at 5:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.