I am using sort fun of arrays and it is showing me error like this is not valid . Help me

import java.util.*;

class power
{
    public static void main(String ar[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int a[]=new int[n];
        for(int i=0;i<n;i++)
            a[i]=sc.nextInt();
        Arrays.sort(a,new Comparator<int []>()
        {
            public int compare(int a1[],int a2[])
            {
                String s1=""+a1[0];
                String s2=""+a2[0];
                return s1.compareTo(s2);
            }
        });
    }
}

1 Answers

2
Elliott Frisch On Best Solutions

You can't write a Comparator<int> because Java primitive types can't be used as generics. You'll need the Integer wrapper type. So change

int a[] = new int[n];

to

Integer a[] = new Integer[n];

And then your comparator should be comparing two Integer(s) (not two int[](s)). Like

Arrays.sort(a, new Comparator<Integer>() {
    public int compare(Integer a1, Integer a2) {
        String s1 = "" + a1;
        String s2 = "" + a2;
        return s1.compareTo(s2);
    }
});

or just

Arrays.sort(a, (x, y) -> String.valueOf(x).compareTo(String.valueOf(y)));