Sorting Java Arrays with Arrays.sort and Comparators
Learn how to sort Java arrays with Arrays.sort and custom comparators, including primitive and object arrays, descending order, performance, and edge cases.

To sort an array in Java, use the Arrays.sort method from java.util.Arrays. This article covers sorting primitive and object arrays, custom ordering with comparators, and the performance and edge-case considerations that affect real code.
Using Arrays.sort for Primitive Arrays
The simplest form is Arrays.sort(int[]), which sorts the entire array in ascending order. For primitive types, Arrays.sort uses a dual-pivot quicksort algorithm. It runs in O(n log n) average time and is not stable, so equal elements may not retain their original relative order. For primitives, that is usually irrelevant.
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
// numbers is now {1, 2, 5, 8, 9}The same method works for char[], byte[], short[], long[], float[], and double[]. For floating-point arrays, -0.0 and 0.0 are treated as distinct, and NaN is placed at the end.
Sorting Object Arrays with Natural Order
For object arrays, Arrays.sort(Object[]) sorts according to the natural ordering of the elements. Each element must implement Comparable; otherwise the method throws ClassCastException at runtime. This overload uses TimSort, a stable, adaptive merge sort, which preserves the relative order of equal elements.
import java.util.Arrays;
String[] names = {"alice", "bob", "charlie"};
Arrays.sort(names);
// names is now {"alice", "bob", "charlie"} (lexicographic order)If the array contains null, Arrays.sort throws NullPointerException because it attempts to compare null with other elements. Handle or remove null values before sorting if they can appear.
Custom Sorting with Comparators
When natural order is not what you need, pass a Comparator to Arrays.sort(T[], Comparator<? super T>). This works for any object type and gives you full control over the ordering logic. Java 8 and later make this concise with lambda expressions and method references.
import java.util.Arrays;
import java.util.Comparator;
String[] words = {"apple", "kiwi", "banana"};
Arrays.sort(words, Comparator.comparingInt(String::length));
// words is now {"kiwi", "apple", "banana"} (shortest first)For descending natural order, use Comparator.reverseOrder():
Arrays.sort(words, Comparator.reverseOrder());The Comparator contract also recommends consistency with equals when the comparator is used by sorted collections such as TreeSet or TreeMap. For Arrays.sort itself, the comparator needs to provide a deterministic total order.
Sorting Subranges of an Array
Both primitive and object overloads provide a range version: Arrays.sort(array, fromIndex, toIndex). The range is half-open: fromIndex is inclusive and toIndex is exclusive. For object arrays, the comparator version has the same range semantics: Arrays.sort(array, fromIndex, toIndex, comparator). This is useful when you need to sort only part of an array.
int[] data = {4, 2, 9, 1, 5};
Arrays.sort(data, 1, 4); // sorts indices 1, 2, and 3
// data becomes {4, 1, 2, 9, 5}Sorting Primitive Arrays in Descending Order
Arrays.sort on primitive arrays only supports ascending order. To sort a primitive array in descending order, you have two common options:
- Sort ascending and then reverse the array manually.
- Convert to a boxed
Integer[], sort with a comparator, and convert back.
The second approach has overhead from boxing and extra memory. The first is more efficient for large arrays.
int[] numbers = {5, 2, 8, 1, 9};
Arrays.sort(numbers);
// reverse in place
for (int i = 0; i < numbers.length / 2; i++) {
int temp = numbers[i];
numbers[i] = numbers[numbers.length - 1 - i];
numbers[numbers.length - 1 - i] = temp;
}
// numbers is now {9, 8, 5, 2, 1}For object arrays, you can simply use Comparator.reverseOrder().
Performance and Stability Considerations
The algorithm used by Arrays.sort depends on the type being sorted. For primitives, it uses a dual-pivot quicksort, which is not stable but has good average performance and low memory overhead. For objects, it uses TimSort, a stable adaptive merge sort that performs well on partially sorted data but requires extra memory for temporary arrays.
Stability matters when you sort an array of objects by multiple keys. If you first sort by name and then by age, a stable sort preserves the name order for equal ages. TimSort provides this guarantee; quicksort does not.
For large arrays, the memory difference can be significant. The object sort may allocate temporary storage up to roughly half the array length in object references, while the primitive sort works in place. If memory is constrained and you only need primitive ordering, avoid boxing to objects just to use a comparator.
Edge Cases and Common Pitfalls
- Null elements:
Arrays.sorton an object array withnullthrowsNullPointerExceptionduring comparison. Filter or handle nulls before sorting. - Empty arrays: Sorting an empty array is a no-op and does not throw.
- Single-element arrays: Also a no-op.
- Concurrent modification:
Arrays.sortis not thread-safe. If other threads can read or modify the array while it is being sorted, use external synchronization or avoid sharing a mutable array. - Floating-point special values:
Float.NaNandDouble.NaNare considered greater than all other values, and-0.0is less than0.0. This can lead to surprising orderings if you do not account for it. - Comparator consistency: If your comparator returns inconsistent results, such as changing based on mutable state, the sort may throw
IllegalArgumentExceptionor produce an incorrect order. Ensure the comparator is deterministic and total.
For custom objects, consider implementing Comparable if there is an obvious natural ordering, but use a Comparator when multiple orderings are possible. The Comparator.comparing factory methods make it easy to build comparators for fields, and you can chain them with thenComparing for secondary keys.
When you need to sort a large primitive array in descending order, the in-place reversal approach is more memory-efficient than boxing. For object arrays, Arrays.sort with a comparator is straightforward and leverages the stable TimSort algorithm.
Try matching browser tools
All toolsSmall utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Java guides
All Java guidesJava Final Keyword: Usage and Behavior
How Java's final keyword works for variables, methods, and classes, with practical examples and decision guidance for using it.
Java Final Variable: Syntax, Behavior, and Use Cases
Understand what a final variable in Java means, how initialization works, and when to use it for constants, immutability, and clearer code.
Java Duration vs Period: When to Use Each
java duration vs period: Compare Java Duration and Period to handle time-based and date-based calculations correctly. Learn syntax, conversion, and pitfalls.
Instance vs Static Variables in Java: Key Differences
Understand the difference between instance and static variables in Java, including memory, lifecycle, and when to use each.
More in Java
All Java guidesThe guides filed next to this one in Java, in library order.