Back to results for “Arrays”
Java › Arrays & Multidimensional Arrays

What utility methods does java.util.Arrays provide for common array operations like sorting, searching, filling, and comparing?

Intermediate

Answer

Arrays provides static utility methods including sort() (in-place sorting, dual-pivot quicksort for primitives, TimSort for objects), binarySearch() (requires a pre-sorted array), fill() (populate all elements with one value), copyOf()/copyOfRange() (create a resized copy), equals()/deepEquals() (element-wise comparison, deepEquals needed for nested arrays), and asList() (a fixed-size List view backed by the array) -- these cover the vast majority of common array manipulation needs without hand-writing loops.
int[] nums = {5, 2, 8, 1, 9};
Arrays.sort(nums);  // {1, 2, 5, 8, 9}
int index = Arrays.binarySearch(nums, 8);  // 3

int[] copy = Arrays.copyOf(nums, 3);  // {1, 2, 5}
int[][] matrix1 = {{1,2},{3,4}};
int[][] matrix2 = {{1,2},{3,4}};
System.out.println(Arrays.equals(matrix1, matrix2));      // false -- compares references of inner arrays
System.out.println(Arrays.deepEquals(matrix1, matrix2));  // true -- recursively compares contents
Real-world example A data-processing utility sorts a large primitive int array using Arrays.sort() (leveraging its highly optimized dual-pivot quicksort implementation) rather than converting to a boxed Integer collection just to use Collections.sort(), avoiding unnecessary boxing overhead for a purely numeric workload.

Common follow-ups: Why does Arrays.equals() give a misleading false result for nested arrays, requiring deepEquals() instead?;What are the performance characteristics of Arrays.sort() for primitives versus objects?