Home > other >  Error in java comparator class while sorting the array?
Error in java comparator class while sorting the array?

Time:06-13

enter image description here

I am getting this error please tell how to correct it

CodePudding user response:

You can simply sort an array in ascending order by:

Arrays.sort(array);

If you need to sort the array in descending order you can use:

Arrays.sort(array, Collections.reverseOrder());

Note: If you gonna use Comparator inside Arrays.sort you probably get :

The method sort(int[]) in the type Arrays is not applicable for the arguments (int[], new Comparator(){})

CodePudding user response:

The return type of compare method is int and you are returning a boolean value.

Modify the code to return an int value.

Also, comparator class requires object datatype. Modify your array from int[] to Integer[]

Integer[] nums = new Integer[]{not, tak, twice};
    Arrays.sort(nums, new Comparator<Integer>() {
        @Override
        public int compare(final Integer o1, final Integer o2) {
            return Math.abs(o1) - Math.abs(o2);
        }
    }

CodePudding user response:

Never give images !!! always code !!!

Java comparator must return an int (as shown in signature)

(edited after comments)

public int compare(Integer o1, Integer o2){
   return Math.abs(o2) - Math.abs(o1);
}

CodePudding user response:

You want to first sort on the absolute values, and when equal on the signed value.

And then the Arrays.sort with a Comparator only is for Object derived classes, not the primitive type int. So you need an Integer[]

Integer[] nums = {not, tak, twice};
Arrays.sort(nums,
    Comparator.comparingInt(n -> Math.abs(n.intValue())
              .thenComparingInt(Integer::intValue));
  • Related