Arrays Sort Comparator Needs Boxing
Primitive arrays sort ascending only; reversing or field-based ordering means boxing to Integer[] and passing a Comparator to Arrays.sort.
Code
import java.util.Arrays;
import java.util.Comparator;
public class SortShapes {
public static void main(String[] args) {
int[] scores = {88, 42, 95, 61};
// primitives have no Comparator overload: ascending is the only mode
Arrays.sort(scores);
System.out.println("ascending: " + Arrays.toString(scores));
// descending requires boxing into Integer[] before a Comparator applies
Integer[] boxed = {88, 42, 95, 61};
Arrays.sort(boxed, Comparator.reverseOrder());
System.out.println("descending: " + Arrays.toString(boxed));
// object arrays compare by field: shorter first, ties broken alphabetically
String[] words = {"pear", "fig", "apple"};
Arrays.sort(words,
Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println("by length: " + Arrays.toString(words));
// range sort: only indices [1, 3) get ordered
int[] partial = {9, 5, 7, 1};
Arrays.sort(partial, 1, 3);
System.out.println("partial: " + Arrays.toString(partial));
}
}What the demo sorts
An int[] goes through Arrays.sort and comes back ascending, the only mode the primitive overloads accept because there is no Comparator parameter for int[]. The same values boxed into Integer[] do take Comparator.reverseOrder(), printing the descending order.
Object arrays get full control: the words sort by comparingInt(String::length) with thenComparing(naturalOrder) as the tie-breaker, so fig precedes pear before any alphabetical check matters. The final call sorts only indices 1 to 3 of a second int[], leaving element 0 untouched.
Points to remember
- Boxing is the price of custom ordering on primitives.
- The range overload treats [from, to) and excludes the to index.
Interactive Tools for This Topic
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Why does descending order need Integer[]?
- Primitive int[] overloads sort ascending only; a Comparator requires object references, so the values must be boxed into Integer[] first, as the second printed line shows.
Report a problem with this exampleOpens a pre-filled issue on GitHub.