0

Suppose I have a method - private static void sort(String[] arr)
Now I want to sort this array using the comparator - String.CASE_INSENSITIVE_ORDER
Is it possible to set this as the default comparator to the String arr before passing
the argument to this function sort. It's like I wont have to change anything inside the sort function to modify its behavior. It's like the comparator gets implanted into
the arr

6
  • 1
    A string array doesn't hold anything but strings Commented Aug 13, 2021 at 15:43
  • 1
    No, an array of strings cannot have its own "default comparator". Commented Aug 13, 2021 at 15:43
  • 1
    No. There is no (good) way to associate a default Comparator with a String[] Commented Aug 13, 2021 at 15:43
  • not sure if that is what you mean, but you can have the method accept a comparator as an optional argument through overloading Commented Aug 13, 2021 at 15:44
  • Could there be some way of making an anonymous class objects out of the string array which has the comparator? Commented Aug 13, 2021 at 15:48

1 Answer 1

1

Arrays are meant to be basic, simple containers.

If you want more features, use a class from the Java Collections Framework.

If your elements are distinct (no duplicates need be tracked), use a NavigableSet implementation. Java bundles two. One is TreeSet.

NavigableSet< String > navSet = new TreeSet<>() ;

By default, the navigable set uses the “natural order” of your objects, by calling their compareTo method. Alternatively, you can pass a Comparator to the constructor, to be used for sorting.

In your case the String class carries a Comparator implementation as a constant: String.CASE_INSENSITIVE_ORDER .

NavigableSet< String > navSet = new TreeSet<>( String.CASE_INSENSITIVE_ORDER ) ;

Caveat: That comparator does not account for locale in sorting your strings. For locale-savvy sorting, use a Collator instead.

You said:

It's like I wont have to change anything inside the sort function to modify its behavior. It's like the comparator gets implanted into the arr

That is exactly what you get by specifying a Comparator for a collection class.

Sign up to request clarification or add additional context in comments.

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.