3

I have the following program

import java.util.*;
public class Test {
    public static void main(String[] args) {
        Integer[] array = { 3, 1, 4, 1, 5, 9 };
        Arrays.sort(array, new Comparator<Integer>() {
            public int compare(Integer i1, Integer i2) {
                return i1 < i2 ? -1 : (i2 > i1 ? 1 : 0);
            }
        });
        System.out.println(Arrays.toString(array));
    }
}

This gives me the output [3, 1, 4, 1, 5, 9]. Why?

0

3 Answers 3

6

because i1 < i2 is the same as i2 > i1 - look what you've written in your compareTo method.

Sign up to request clarification or add additional context in comments.

Comments

3
i1 < i2 
i2 > i1 

These are the same.

Comments

1

You test for i1 < i2, and, if it fails, you test NOT for i1 > i2, but for i2 > i1.

Change your comparator to

   return i1 < i2 ? -1 : (i1 > i2) ? 1 : 0;

ADDED

In an attempt to contribute something new to the two other answers that said the same thing and beat me to the punch, most of the wrapper classes have built in compareTo() methods to save you from any thought. e.g., your comparator could just call Integer.compareTo(), i.e.

 return i1.compareTo(i2);

1 Comment

Probably should be using compareTo() anyway since those magic numbers don't look healthy; +1 for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.