Arrays.sort and Sorting
Sort primitive and object arrays.
Why a Utility Class
Arrays in Java are objects, but they have very few built-in methods. The java.util.Arrays class fills the gap with static helper methods for sorting, searching, comparing, copying, and printing arrays.
- Import it with
import java.util.Arrays; - Every method is
static, so you call them on the class itself:Arrays.sort(...)
Sorting a Primitive Array
Arrays.sort(int[]) sorts the array in place using a fast dual-pivot quicksort. There is no return value; the original array is rearranged.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] nums = {5, 2, 8, 1, 9, 3};
Arrays.sort(nums);
System.out.println(Arrays.toString(nums));
}
}All lessons in this course
- Arrays.sort and Sorting
- Arrays.binarySearch
- Arrays.fill and copyOf
- Arrays.equals and toString