The Arrays class
The Arrays class from the java.util package collects ready-made methods for working with arrays: printing, sorting, filling, copying and comparing. A package is a group of related classes. In the short program form java.util is available automatically; in the classic form you need the line import java.util.Arrays;.
toString
Arrays.toString() turns an array into a readable string. Every example below uses it to show the result:
void main() {
String[] cities = {"Rome", "Paris", "Berlin"};
IO.println(Arrays.toString(cities));
}Output:
[Rome, Paris, Berlin]sort
Arrays.sort() sorts an array in ascending order. It changes the array itself and returns nothing. Strings are sorted alphabetically:
void main() {
int[] prices = {40, 15, 99, 3};
Arrays.sort(prices);
IO.println(Arrays.toString(prices));
String[] names = {"Oleg", "Anna", "Maria"};
Arrays.sort(names);
IO.println(Arrays.toString(names));
}Output:
[3, 15, 40, 99]
[Anna, Maria, Oleg]To sort in a different order, for example descending or by string length, you need a comparator — see the lesson on sorting collections.
fill
Arrays.fill() writes one value into every element of an array. It is useful when the default value does not fit:
void main() {
char[] line = new char[10];
Arrays.fill(line, '-');
IO.println(new String(line));
}Output:
----------new String(line) builds a string from a character array. There is also a version for part of an array: Arrays.fill(line, 0, 3, '*') fills only indexes 0 to 2.
Copying
An array's length cannot change, but you can make a copy of the size you need. Arrays.copyOf() takes the beginning of the array and pads the copy with default values if it is longer. Arrays.copyOfRange() copies a slice from an index inclusive to an index exclusive:
void main() {
int[] numbers = {1, 2, 3, 4, 5};
IO.println(Arrays.toString(Arrays.copyOf(numbers, 3)));
IO.println(Arrays.toString(Arrays.copyOf(numbers, 7)));
IO.println(Arrays.toString(Arrays.copyOfRange(numbers, 1, 4)));
}Output:
[1, 2, 3]
[1, 2, 3, 4, 5, 0, 0]
[2, 3, 4]The original array does not change.
Comparing and searching
Arrays.equals() compares arrays element by element. Arrays.binarySearch() quickly finds the index of a value, but only in a sorted array:
void main() {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
IO.println(Arrays.equals(a, b));
int[] sorted = {10, 20, 30, 40};
IO.println(Arrays.binarySearch(sorted, 30));
}Output:
true
2If the value is missing, binarySearch() returns a negative number.
Common mistake
Arrays cannot be compared with == or with the array's own equals() method. Both check whether it is the same object, not whether the contents match:
void main() {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
IO.println(a == b);
IO.println(a.equals(b));
IO.println(Arrays.equals(a, b));
}Output:
false
false
trueTo compare contents always use Arrays.equals(), and Arrays.deepEquals() for two-dimensional arrays.