The java.util.Arrays
utility class provides a variety of methods for performing common array operations efficiently. It includes methods for sorting, searching, comparing, filling, and converting arrays to strings. Here’s a breakdown of some of the most useful methods in the Arrays
class:
The Arrays.sort()
method is used to sort elements in ascending order. It can sort arrays of primitives or objects that implement the Comparable
interface.
int[] numbers = {4, 2, 7, 1, 9};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Outputs: [1, 2, 4, 7, 9]
For descending order, you can use Arrays.sort()
with a custom Comparator
(only for object arrays).
The Arrays.binarySearch()
method searches for a specified element in a sorted array using binary search, which is fast and efficient. This method returns the index of the element if it exists; otherwise, it returns a negative value.
int[] numbers = {1, 2, 4, 7, 9};
int index = Arrays.binarySearch(numbers, 4); // Returns 2 (index of element 4)
The Arrays.equals()
method compares two arrays to see if they contain the same elements in the same order. It works for both primitive and object arrays.
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean areEqual = Arrays.equals(arr1, arr2); // Returns true
For multi-dimensional arrays, Arrays.deepEquals()
performs a deep comparison, checking that elements are equal at all levels.
The Arrays.fill()
method sets all elements in an array to a specified value, which is useful for initializing or resetting arrays.
int[] arr = new int[5];
Arrays.fill(arr, 10); // Sets all elements to 10
The Arrays.copyOf()
and Arrays.copyOfRange()
methods create new arrays from an existing array. copyOf()
copies the whole array up to a specified length, while copyOfRange()
allows you to copy a range of elements.
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, 3); // Copy first 3 elements
int[] rangeCopy = Arrays.copyOfRange(original, 1, 4); // Copy elements 1 to 3
The Arrays.toString()
method provides a string representation of an array, which is helpful for printing arrays easily.
int[] numbers = {1, 2, 3};
System.out.println(Arrays.toString(numbers)); // Outputs: [1, 2, 3]
For multi-dimensional arrays, Arrays.deepToString()
can be used to display all elements.
Arrays.setAll()
:
Initializes or modifies all elements based on a specified function.
int[] arr = new int[5];
Arrays.setAll(arr, i -> i * 2); // Sets each element to its index * 2
Arrays.asList()
:
Converts an array to a List
, allowing you to use collection operations. Note that the list is fixed-size, so you cannot add or remove elements.
String[] arr = {"apple", "banana", "cherry"};
List<String> list = Arrays.asList(arr);