Lesson · Arrays
java.util.Arrays: the standard toolkit
11 min readArrays Utility Class
The utility class you are allowed to be lazy with: sort, search, fill, copy, compare, stream. With the behaviours that surprise people called out as they are used.
sort: one call, five truths
Arrays.sort(ints) is dual-pivot quicksort: in place, average O(n log n), and it mutates the argument. Arrays.sort(objects) is TimSort: stable (equal elements keep their order), which is why sorting by one key then another composes. Sorting a long[] or double[] behaves the same way, primitives by value.
Sorting objects needs an ordering: the elements must implement Comparable, or a Comparator must be supplied. Arrays.sort(strings) uses String's natural lexicographic order; Arrays.sort(words, Comparator.comparingInt(String::length)) sorts by length stably. A range can be sorted too: sort(a, from, to) sorts only [from, to).
Arrays utility lab
pick a callThe argument is sorted itself, no copy returned. For primitives the algorithm is dual-pivot quicksort; for objects it is TimSort: stable, so equal elements keep their order.
Sort before search, remember asList is a view, and the utility class stops producing surprises.
binarySearch: fast, exact, and pedantic
Arrays.binarySearch(sorted, key) returns the index when found and a negative value when not: -(insertion point) - 1, so -2 means the key belongs at index 1. The two facts to internalise: the array MUST be sorted first (undefined results otherwise, silently), and the return protocol encodes both the hit and the miss in one int.
Calling binarySearch on an unsorted array is a favourite interview trap, because it does not throw, it lies: answers appear correct for small inputs and wrong at scale. Sort first, search twice: both are single calls.
fill, copyOf, copyOfRange
Arrays.fill(a, 7) writes the same value into every slot; a range overload fills [from, to) only. Handy for initialising freshly allocated arrays, and required for clearing sensitive buffers after use (Arrays.fill(password, '\0')).
Arrays.copyOf(a, newLength) returns a new array: longer pads with defaults (zero, false, null), shorter truncates. Arrays.copyOfRange(a, from, to) copies a slice. Both are the JDK 6 replacement for the verbose arraycopy dance, which remains for cases where an existing destination array must receive the data: System.arraycopy(src, srcPos, dest, destPos, length).
equals, toString, deep variants, and streams
Arrays.equals(a, b) compares contents (null-safe, element by element); the deep variants recurse into nested arrays: Arrays.deepEquals, Arrays.deepToString. Arrays.toString(a) renders [1, 2, 3] for printing; for anything with inner arrays the deep version is the correct one.
Since Java 8, Arrays.stream(a) opens the box on the stream API: Arrays.stream(scores).filter(s -> s >= 90).average(). Sums, maxima and reductions on arrays collapse to one-liners, and toArray brings results back. The streams topic revisits this; for the arrays chapter it is enough that the bridge exists and costs nothing to cross.
Arrays.asList returns a FIXED-SIZE list, not a copy
Arrays.asList(a) is a view over the same backing array: set() writes through to it, add() and remove() throw UnsupportedOperationException, and the original array stays the source of truth. Need a mutable list? new ArrayList<>(Arrays.asList(a)). Need a list from literal items? List.of(...) for an immutable one.
Interview angles
What does binarySearch return when the key is absent?+
A negative number: -(insertion point) - 1. For a key that belongs at index 3, the answer is -4. One return value encodes both found-indices (non-negative) and insertion points, which callers must decode deliberately.
Is Arrays.sort stable?+
For object arrays yes: TimSort preserves the order of equal elements, so chained sorts by different keys compose. For primitive arrays stability is meaningless (identical values are indistinguishable), and the sort is the faster dual-pivot quicksort.
Arrays.asList versus List.of?+
asList is a fixed-size view over your array: set works, add/remove throw, and writes reflect into the array. List.of creates an immutable copy-like list: no set, no add, and rejecting even a null element.