Why I can't use Comparator to sort primitives?

北城余情 提交于 2019-12-04 15:25:39

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!