Divyaanand Sinha
Divyaanand Sinha

Reputation: 396

getting an error while using Arrays.sort() in Java

I am using ->

String ar[]=new String[n];
Arrays.sort(ar,new Comparator<String>());

I am getting the error as shown below

The method sort(T[], Comparator<? super T>) in the type Arrays is not applicable for the arguments (String[], Comparator<String>)

What should i do??

Upvotes: 2

Views: 418

Answers (2)

k0staa
k0staa

Reputation: 342

Apart from providing your own implementation of Comparator (as seen in @SURESH ATTA answer) you can just simply use fact that String is implementing Comparable interface (Source) and you can use sort method like this:

String[] strings = { " A ", " D ", " E ", " B ", " Z " };
Arrays.sort(strings);

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Comparator is an interface. Hence you need to instatiate it annonymously and provce implementation

Arrays.sort(ar, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            // TODO Auto-generated method stub
            return o1.compareTo(o2);
        }
    });

Upvotes: 4

Related Questions