Chen
Chen

Reputation: 53

Array in Desending Order

Error:(33, 15) java: no suitable method found for sort(int[],java.util.Comparator<java.lang.Object>)
    method java.util.Arrays.<T>sort(T[],java.util.Comparator<? super T>) is not applicable
      (inference variable T has incompatible bounds
        equality constraints: int
        lower bounds: java.lang.Object)
    method java.util.Arrays.<T>sort(T[],int,int,java.util.Comparator<? super T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

I don't understand why num in Array.sort(num, Collections.reverseOrder()) is wrong?

    Scanner s = new Scanner(System.in);

    int a = s.nextInt();
    int b = s.nextInt();
    int c = s.nextInt();

    int[] num = new int[3];

    num[0] = a;
    num[1] = b;
    num[2] = c;


    Arrays.sort(num, Collections.reverseOrder());
    for (int i = 0; i < num.length; i++) {
        System.out.println(num[i] + " ");
    }
    

is there any other way to solve it?

Upvotes: 0

Views: 96

Answers (3)

user13510609
user13510609

Reputation:

There is no Arrays.sort method that accepts an int[] and a Comparator - the one that accepts a Comparator requests an array of Object or of any subclass of Object (example Integer[]).

Background information: a type variable (generic) cannot reference a primitive, so

<T> void sort(T[], Comparator<? super T>)

is not valid for int[].

Upvotes: 2

Frida
Frida

Reputation: 106

I can recommend you to use Java 8 Streams. I would do it the following:

Stream.of(num).sorted(Collections.reverseOrder());

If you want to use Arrays.sort() then there is just the optionen for int[] as first parameter to give two more parameters (int fromIndex, int toIndex), which is the reason why you are getting an exception using (int[], Comparator) parameter.

Upvotes: 1

Arunbh Yashaswi
Arunbh Yashaswi

Reputation: 1205

Use ArrayList instead

import java.util.*;
public class Main {
   public static void main (String[] args) {
     Scanner s = new Scanner(System.in);

    int a = s.nextInt();
    int b = s.nextInt();
    int c = s.nextInt();

      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(a);
      list.add(b);
      list.add(c);
      Comparator c1 = Collections.reverseOrder();
      Collections.sort(list,c1);
      System.out.println("Desending Order : " + list);
   }
}

This will do the trick. You can use array in intialization.

The code underneath worked for me using Array

import java.util.Arrays; 
import java.util.Collections; 

public class Main 
{ 
    public static void main(String[] args) 
    { 
        Integer[] arr = {2, 1, 3}; 
        Arrays.sort(arr, Collections.reverseOrder()); 
        System.out.printf("Desending Order : %s", Arrays.toString(arr)); 
    } 
} 

Upvotes: 0

Related Questions