2

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??

1
  • 1
    Comparator is an interface. How exactly are you instanciating it?
    – Mureinik
    Oct 18, 2015 at 17:02

2 Answers 2

4

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);
        }
    });
0

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.