Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output using comparator

Tags:

java

sorting

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?

like image 992
Saurabh Kumar Avatar asked Feb 03 '26 04:02

Saurabh Kumar


1 Answers

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

like image 84
asenovm Avatar answered Feb 05 '26 22:02

asenovm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!