Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my arraylist not getting sorted using comparator interface?

So i tried sorting an arraylist which consists of only integer elements in descending order using comparator interface but after printing the array list it shows the elements in the order in which input was given.

here's my code...

import java.io.*;
import java.util.*;
public class Test {
    public static class Sort implements Comparator<Integer>{
        public int compare(Integer a,Integer b){
            if(a<b){
                return 1;
            }
            return 0;
        }
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n=Integer.parseInt(br.readLine());
        ArrayList<Integer> arraylist=new ArrayList<>();
        for(int i=0;i<n;i++){
            arraylist.add(Integer.parseInt(br.readLine()));
        }
        Collections.sort(arraylist,new Sort());
        System.out.println(arraylist);
        br.close();
    }
}

So what i learnt is that if the compare method returns a positive value then swapping of the objects take place. So i returned 1 if a<b for sorting the array in descending order. Where did i go wrong?

like image 842
manofculture Avatar asked Jul 22 '26 03:07

manofculture


1 Answers

As the Comments discuss, your code violates the terms of the Comparator contract. Per Jon Skeet, the Javadoc explains that "The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y."

And, you are working too hard.

When you want to reverse the order, descending rather than ascending, simply call Comparator#reversed. This call returns a new Comparator object for you to use.

Since Integer class implements Comparable, you need not define an initial comparator. Simply call Comparator#reverseOrder. This call reverses the natural order of the objects.

List< Integer > myList = new ArrayList <> ( List.of( 7 , 1 , 42 ) ) ;
myList.sort( Comparator.reverseOrder() );

See this code run live at IdeOne.com.

[7, 1, 42]

[42, 7, 1]

like image 91
Basil Bourque Avatar answered Jul 24 '26 18:07

Basil Bourque



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!