开发者

Why I can't use Comparator to sort primitives?

As Java 5 have autoboxing, why I can't use Comparator to sort primitiv开发者_如何学Goes? 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜