Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can't use Comparator to sort primitives?

As Java 5 have autoboxing, why I can't use Comparator to sort primitives? An int wouldn't be wrapped into a Integer?

like image 898
The Student Avatar asked Dec 16 '22 18:12

The Student


2 Answers

Arrays.sort(..) have dedicated overloadings for sorting primitive arrays.

If you need any special sorting rules apart from the standard ones, I'm afraid you'd have to use autoboxing. In addition to that, you'd have to transform your array to Integer[], because int[] is not autoboxed.

And if you are not talking about arrays, but about collections - then you have no choice - collections can hold only objects.

like image 134
Bozho Avatar answered Jan 04 '23 17:01

Bozho


Because you cannot parameterise a Comparator<T> -- or any other parameterised type -- with a primitive type.

Yes this is massively annoying... you can't make a List<int> or a Map<String, boolean> etc, and you can't write generic methods that work for both object types and primitives. You have to have dedicated methods for each of the 8 primitive types. But that's the design we've been stuck with since Java 1. Blame James Gosling ;-)

As Bozho points out, Arrays.sort(...) provides all the sorting methods you need.

like image 37
Neil Bartlett Avatar answered Jan 04 '23 19:01

Neil Bartlett