The Arrays class groups static methods to operate with arrays, such as sorting, searching, copying, or comparing their elements.
Arrays are rigid structures and do not have their own methods for these operations.
They are rigid structures. If you want to sort the numbers in an array, the array doesn’t know how. If you want to search for a value, you have to traverse it yourself. If you try to print it directly, you get a strange code like [I@15db9742.
In the old days, you had to write sorting algorithms yourself (like Bubble Sort or Quicksort). Nowadays, that’s forbidden in production. Java already comes with an optimized Swiss Army knife for this dirty work: the java.util.Arrays class.
This class is a set of static methods (tools) that make our lives much easier.
Printing an array
You’ve probably tried this and been disappointed:
int[] numeros = {1, 2, 3};
System.out.println(numeros); // Output: [I@6d06d69c (Memory reference)Since arrays inherit the representation from Object, Java shows the internal type name and a hexadecimal hash. To see the content, we use Arrays.toString():
import java.util.Arrays; // Important!
System.out.println(Arrays.toString(numeros));
// Output: [1, 2, 3]What about multidimensional arrays?
If you use toString on a multidimensional array (array of arrays), you will see the references of the rows. To see all the content recursively, use Arrays.deepToString(matrix).
Sorting with Arrays.sort()
Sorting data is one of the most expensive tasks in computing. Don’t reinvent the wheel. Java’s sort method is extremely fast (it uses a variant of Dual-Pivot Quicksort for primitives and Timsort for objects).
int[] unsorted = {5, 1, 9, 3};
// Sorts the original array (Modifies the array, does not return a new one)
Arrays.sort(unsorted);
System.out.println(Arrays.toString(unsorted));
// Output: [1, 3, 5, 9]Sorting parts of an array
We can also sort only a range (fromIndex inclusive, toIndex exclusive).
// Sort only from index 0 to 2
Arrays.sort(arr, 0, 3);Binary Search (binarySearch)
If you want to find an element in an array, the normal way is to use a for loop and check one by one. This is called Linear Search and has a cost of . If you have 1 million elements, in the worst case you’ll make 1 million checks.
Binary Search is much smarter. It keeps dividing the array in half. Is it greater or smaller? And it discards the half. Its cost is . With 1 million elements, it finds the target in just 20 steps.
To use it:
int[] numbers = {10, 20, 30, 40, 50};
// Returns the index where the element is located
int position = Arrays.binarySearch(numbers, 30);
System.out.println("The value 30 is at position: " + position); // 2Requirement:
For binarySearch to work, the array MUST be sorted beforehand.
If you use binary search on an unsorted array, the result is unpredictable (and incorrect).
What happens if it’s not found?
The method returns a negative number. But not just any negative number. It returns:
(-(insertion point) - 1)
That is, it tells you where the number should go if you wanted to insert it in sorted order.
Comparing (equals and compare)
Remember that array1 == array2 compares whether they are the same object. If we want to know if they have the same content, we use Arrays.equals().
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b); // false (Different objects)
System.out.println(Arrays.equals(a, b)); // true (Same content)Since Java 9, we also have Arrays.compare(a, b), which returns:
0: If they are identical.< 0: Ifais “less” (lexicographically) thanb.> 0: Ifais “greater” thanb.
Filling and copying (fill and copyOf)
Two other utilities that save us from writing for loops:
Arrays.fill(arr, value): Fills the entire array (or a range) with the same value. Useful for resetting data.Arrays.copyOf(original, newLength): Creates a new array by copying data from the original. If the new size is larger, it fills the positions with the default value for the type (0,false, ornull).
int[] source = {1, 2, 3};
int[] bigger = Arrays.copyOf(source, 5);
// bigger is [1, 2, 3, 0, 0]