Question

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

Was it helpful?

Solution

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);

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top