Sorting and Arrays
java.util.Arrays is a class of static methods for arrays: sort, search, copy, fill, compare and print. It is part of the standard library and needs no dependency, and its methods are the ones a hand-written loop would be compared against.
Arrays.sort
sort orders the array in place, using the natural order of its elements: numeric for the primitive types, lexicographic for strings. It returns nothing, because the array it sorted is the array it was given.
The file Sort.java:
import java.util.Arrays;
public class Sort {
public static void main(String[] args) {
int[] values = {42, 8, 15, 4, 23, 16};
Arrays.sort(values);
System.out.println(Arrays.toString(values));
System.out.println("15 at " + Arrays.binarySearch(values, 15));
System.out.println("7 at " + Arrays.binarySearch(values, 7));
String[] names = {"Grace", "Ada", "Alan"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
}
}
javac -Xlint:all Sort.java
java Sort
[4, 8, 15, 16, 23, 42]
15 at 2
7 at -2
[Ada, Alan, Grace]
Arrays.toString writes the elements in brackets with a comma and a space between them, which is the form every later lesson uses to show an array. Without it, println(values) would print the type and a hash code, not the numbers.
Arrays.binarySearch
A binary search halves the range on every step and needs a sorted array. The index 2 for 15 is the position in the sorted array. A missing value returns a negative number that encodes where it would be inserted: the bitwise complement of the insertion point. For 7 that point is 1, so the result is -1 - 1 = -2.
Searching an unsorted array with binarySearch gives an answer that means nothing, because the algorithm assumes the order. Sort first, or use the linear search of the previous lesson.
copyOf and copyOfRange
copyOf(array, newLength) returns a new array of the requested length. Shorter truncates, longer pads with the default value of the element type, and the original is untouched. copyOfRange(array, from, to) copies from the from index inclusive to to exclusive.
import java.util.Arrays;
public class CopyFill {
public static void main(String[] args) {
int[] values = {1, 2, 3, 4, 5};
int[] longer = Arrays.copyOf(values, 7);
System.out.println(Arrays.toString(longer));
int[] middle = Arrays.copyOfRange(values, 1, 4);
System.out.println(Arrays.toString(middle));
int[] filled = new int[4];
Arrays.fill(filled, 9);
System.out.println(Arrays.toString(filled));
int[] copy = Arrays.copyOf(values, values.length);
copy[0] = 99;
System.out.println(Arrays.toString(values));
}
}
javac -Xlint:all CopyFill.java
java CopyFill
[1, 2, 3, 4, 5, 0, 0]
[2, 3, 4]
[9, 9, 9, 9]
[1, 2, 3, 4, 5]
The two zeros are the padding a longer copy gets. The range 1, 4 gives three elements, because the second index is exclusive, the same rule substring follows. The last line proves that the copy is a separate array: changing it left the original at 1.
fill
fill writes one value into every element, or into a range. It is the quick way to reset a buffer between uses, and it works on the array in place. A fill of a range follows the same inclusive start and exclusive end as copyOfRange.
equals and deepToString
Two arrays with the same elements are still two objects, so == is false. Arrays.equals compares the contents element by element, and Arrays.deepToString prints an array of arrays instead of printing a hash code for each inner array.
import java.util.Arrays;
public class Equality {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println("a == b: " + (a == b));
System.out.println("equals: " + Arrays.equals(a, b));
int[][] grid = {{3, 1}, {2, 4}};
System.out.println("deep: " + Arrays.deepToString(grid));
Arrays.sort(grid[0]);
System.out.println("after a sort: " + Arrays.deepToString(grid));
}
}
javac -Xlint:all Equality.java
java Equality
a == b: false
equals: true
deep: [[3, 1], [2, 4]]
after a sort: [[1, 3], [2, 4]]
grid[0] is one inner array, so Arrays.sort(grid[0]) sorts just the first row and leaves the second alone. A sort of the whole grid would sort the rows by their contents, which is a different operation and the subject of the comparator lesson in the collections part.
Exercises
- Sort the names in Sort.java in reverse order by sorting and then reversing the array by hand.
- Search for a value that is smaller than every element and one that is larger, and read the two negative results.
- Copy an array to a longer one and fill the new elements with -1 instead of leaving zeros.
- Compare two arrays of strings with ==, with Arrays.equals and with Arrays.deepEquals.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Arrays.sort(values)return?Answer
Nothing: it sorts the array in place
sort has a void return type and reorders the array it was given.
-
What does
Arrays.binarySearchrequire of the array?Answer
That it is sorted
The halving only works when the order is known, so an unsorted array gives a meaningless answer.
-
What does a negative result from
Arrays.binarySearchmean?Answer
The value is absent, and the complement is the insertion point
The result is -1 - insertionPoint, so -2 means the value would be inserted at index 1.
-
What does this program print?
import java.util.Arrays; public class Q1 { public static void main(String[] args) { int[] values = {3, 1, 2}; Arrays.sort(values); System.out.println(Arrays.toString(values)); } }Answer
[1, 2, 3]
sort orders the three values and toString writes them in brackets.
-
What does this program print?
import java.util.Arrays; public class Q2 { public static void main(String[] args) { int[] values = {10, 20}; int[] longer = Arrays.copyOf(values, 4); System.out.println(Arrays.toString(longer)); } }Answer
[10, 20, 0, 0]
The extra elements of a longer int array are padded with zero.
-
What does this program print?
import java.util.Arrays; public class Q3 { public static void main(String[] args) { int[] values = {1, 2, 3, 4, 5}; System.out.println(Arrays.toString(Arrays.copyOfRange(values, 2, 4))); } }Answer
[3, 4]
The range starts at index 2 inclusive and ends at index 4 exclusive, giving elements 3 and 4.
-
What does this program print?
import java.util.Arrays; public class Q4 { public static void main(String[] args) { int[] values = new int[3]; Arrays.fill(values, 7); System.out.println(Arrays.toString(values)); } }Answer
[7, 7, 7]
fill writes the value into every element of the array.
-
What does this program print?
import java.util.Arrays; public class Q5 { public static void main(String[] args) { int[] a = {1, 2}; int[] b = {1, 2}; System.out.println((a == b) + " " + Arrays.equals(a, b)); } }Answer
false true
The references differ, so == is false, while the contents are equal.
-
What does this program print?
import java.util.Arrays; public class Q6 { public static void main(String[] args) { int[] values = {5, 1, 4, 2}; Arrays.sort(values); System.out.println(Arrays.binarySearch(values, 4)); } }Answer
2
The sorted array is [1, 2, 4, 5] and 4 is at index 2.
-
What does
Arrays.deepToStringprint for an array of arrays?Answer
The elements of the inner arrays, nested in brackets
deepToString descends into the inner arrays, while toString prints their reference text.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev