Home > OS >  Why is my arraylist not getting sorted using comparator interface?
Why is my arraylist not getting sorted using comparator interface?

Time:01-09

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?

CodePudding user response:

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]

CodePudding user response:

Your code fails because you did not return value "-1" and return "0" is not in else statement. So when you performing sort() function it return always "0" for every comparison.

Simply just rewrite an if statement and it works fine.

See example below:

public static class Sort implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
        if (a < b) {
            return 1;
        } else if (a == b) {
            return 0;
        } else return -1;
    }
}
  •  Tags:  
  • Related