Saurabh Kumar
Saurabh Kumar

Reputation: 16651

Unexpected output using comparator

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?

Upvotes: 3

Views: 153

Answers (3)

user949300
user949300

Reputation: 15729

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

Upvotes: 1

asenovm
asenovm

Reputation: 6517

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

Upvotes: 6

James Montagne
James Montagne

Reputation: 78650

i1 < i2 
i2 > i1 

These are the same.

Upvotes: 3

Related Questions