How to Use Arrays.sort in Java: Simple Guide
Use
Arrays.sort(array) to sort an array in Java in ascending order. It works for arrays of primitives and objects that implement Comparable. For custom sorting, use Arrays.sort(array, Comparator).Syntax
The basic syntax to sort an array is:
Arrays.sort(array): Sorts the array in ascending order.Arrays.sort(array, fromIndex, toIndex): Sorts a range within the array.Arrays.sort(array, Comparator): Sorts objects using a custom rule.
java
import java.util.Arrays; // Sort entire array Arrays.sort(array); // Sort part of array Arrays.sort(array, fromIndex, toIndex); // Sort with custom comparator Arrays.sort(array, (a, b) -> a.compareTo(b));
Example
This example shows how to sort an integer array and a string array using Arrays.sort. The integer array is sorted in ascending order, and the string array is sorted alphabetically.
java
import java.util.Arrays; public class SortExample { public static void main(String[] args) { int[] numbers = {5, 3, 8, 1, 2}; String[] fruits = {"banana", "apple", "orange"}; Arrays.sort(numbers); Arrays.sort(fruits); System.out.println("Sorted numbers: " + Arrays.toString(numbers)); System.out.println("Sorted fruits: " + Arrays.toString(fruits)); } }
Output
Sorted numbers: [1, 2, 3, 5, 8]
Sorted fruits: [apple, banana, orange]
Common Pitfalls
Common mistakes when using Arrays.sort include:
- Trying to sort arrays of objects that do not implement
Comparablewithout providing aComparator. - Assuming
Arrays.sortsorts in descending order by default (it sorts ascending). - Modifying the array while sorting, which can cause unexpected results.
java
import java.util.Arrays; import java.util.Comparator; public class SortPitfalls { public static void main(String[] args) { // Wrong: sorting objects without Comparable or Comparator // class Person {} // no Comparable // Person[] people = {new Person(), new Person()}; // Arrays.sort(people); // This causes compile error // Right: use Comparator for custom sorting String[] words = {"pear", "apple", "orange"}; Arrays.sort(words, Comparator.reverseOrder()); System.out.println("Descending order: " + Arrays.toString(words)); } }
Output
Descending order: [pear, orange, apple]
Quick Reference
| Method | Description |
|---|---|
| Arrays.sort(array) | Sorts entire array in ascending order |
| Arrays.sort(array, fromIndex, toIndex) | Sorts part of array from fromIndex (inclusive) to toIndex (exclusive) |
| Arrays.sort(array, Comparator) | Sorts array using custom Comparator |
| Arrays.toString(array) | Converts array to readable string for printing |
Key Takeaways
Use Arrays.sort(array) to sort arrays in ascending order easily.
For objects, ensure they implement Comparable or provide a Comparator.
Arrays.sort modifies the original array in place.
Use Arrays.sort(array, Comparator) for custom sorting rules.
Remember to import java.util.Arrays before using Arrays.sort.