문제

Does anybody see library that can solve this problem? Default array sorting can't deal with custom comparators.

도움이 되었습니까?

해결책

You can use Comparator on the Objects only.You can't on the primitive types.
By using ArrayUtils class you can convert primitive array to wrapper and vice-versa .
So Use Apache Commons ArrayUtils class.

Integer objectArray = ArrayUtils.toObject(array);   
Arrays.sort(objectArray,new MyComparator());
int[] sortedArray = ArraysUtils.toPrimitive(objectArray);

다른 팁

Well, this doesn't require an answer but I think I must make you understand the reason behind this.

All the basic data types or primitive data types can only be compared in the order of their natural ordering. This is enforced by the language specification.

Natural Ordering: means that the obvious way how a group is arranged in nature. For e.g. if you consider natural numbers it is always true that 1 < 2 < 3 < ... < 10 and same is the case with other primitives like char etc.

This also makes a lot of sense and helps in optimization, because the primitive data types are used in the language in lot of places (like loop counters, switch statements etc) and the compiler can actually optimize a lot of things if it can assume the natural order of a type of variables.

There are many more points, but I am sure you got the reason why Arrays default sort doesn't provide custom Comparator for primitive data types.

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