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

Community
  • 1
  • 1
theUg
  • 1,284
  • 2
  • 9
  • 14

2 Answers2

3

You can use the built in comparator String.CASE_INSENSITIVE_ORDER:

Arrays.sort(args, 1, args.length, String.CASE_INSENSITIVE_ORDER);
Faruk Sahin
  • 8,406
  • 5
  • 28
  • 34
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.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Non-trivial indeed. :) However, nice to know the options available for more advanced stuff. – theUg Nov 12 '12 at 01:24