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
1 Answer
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.
Comparatorwith aString[]