0

Possible Duplicate:
How to properly sort upper and lowercase Strings in Array in Android?

I have to sort subset of CLI arguments alphabetically. So, to sort subset the following code is used:

// Ignore args[0], sort the rest
Arrays.sort(args, 1, args.length);

And to sort ignoring case, I have to use some sort of comparator object. To sort subset with comparator, there is the following method signature:

Arrays.sort(array, from, to, comp);

Can it be done without creating comparator object on separate line, and include it in the Arrays.sort() signature (i.e. neat and understandable enough)?

0

2 Answers 2

3

You can use the built in comparator String.CASE_INSENSITIVE_ORDER:

Arrays.sort(args, 1, args.length, String.CASE_INSENSITIVE_ORDER);
Sign up to request clarification or add additional context in comments.

Comments

2

You can define and initialise an anonymous class implementing Comparator e.g.

new Comparator<Whatever> {
   public int compare(Whatever w1, Whatever w2) {
      // implementation
   }
   // etc...
}

and do this inline i.e. within the Arrays.sort() method.

Arrays.sort(array, from, to, new Comparator<Whatever>{....});

The downside is readability if the comparator implementation is non-trivial, and, of course, you can't use that comparator elsewhere. However if the comparator is particularly small, it may aid readability since the implementation is clearly visible.

1 Comment

Non-trivial indeed. :) However, nice to know the options available for more advanced stuff.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.