문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top