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? Commented 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);
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.