As Java 5 have autoboxing, why I can't use Comparator to sort primitives? An int
wouldn't be wrapped into a Integer
?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With