Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 201 ยท Arrays

The Arrays Class

Master java.util.Arrays - toString, sort with comparators, binarySearch, fill, setAll, copyOf, equals and deepEquals, asList pitfalls, stream, mismatch and compare.

In the last two lessons you wrote loops to print, copy, search and compare arrays. You'll still write loops like that, but for the everyday jobs Java ships a ready-made toolbox: the java.util.Arrays class. It's a collection of static methods, so you never create an Arrays object. You just call Arrays.sort(scores) or Arrays.toString(scores).

These methods are tested, fast and clear to readers. A single Arrays.sort replaces a dozen lines of hand-written sorting, and it's faster than anything you'd write casually. This lesson walks through the methods you'll actually use, grouped by job, and points out the traps, especially the infamous Arrays.asList.

In a full class, add import java.util.Arrays;. Compact source files (void main()) import it automatically.

Printing: toString and deepToString

You've already met these two. Arrays.toString formats a one-dimensional array as [a, b, c]; Arrays.deepToString also descends into nested arrays:

Java
int[] flat = { 3, 1, 2 };
int[][] nested = { { 1, 2 }, { 3 } };

Arrays.toString(flat);        // "[3, 1, 2]"
Arrays.deepToString(nested);  // "[[1, 2], [3]]"
Arrays.toString(nested);      // "[[I@..., [I@...]"  (row references)
Arrays.toString(null);        // "null", no exception

Both work for every element type: primitives, String and any object (whose own toString is used).

Sorting

Arrays.sort(array) sorts the whole array in place into ascending order. Numbers sort numerically, char by its code, and String alphabetically by Unicode value, which puts every uppercase letter before every lowercase one:

Java Sorting numbers, strings and ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The two-index form sort(array, from, to) sorts only the range from from up to, not including, to. Every range method in Arrays uses this "from inclusive, to exclusive" rule, just like String.substring.

Under the hood, primitive arrays use a tuned dual-pivot quicksort, and object arrays use a stable merge sort (TimSort). Stable means equal elements keep their original relative order, which matters when you sort records by one field after another.

Custom order with a Comparator

For object arrays you can pass a Comparator that defines the order. Comparator has factory methods, so you don't need to write one by hand yet:

Java Sorting by length, in reverse, and by two keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

String::length is a method reference meaning "call length() on each element"; you'll learn the syntax in Method References, and the whole comparator toolkit in Sorting with Comparable and Comparator. Notice the "by length" line: Rome, Oslo and Lima all have four letters, and the stable sort kept them in the order they had after the reverse sort.

Comparators only work with object arrays. There is no Arrays.sort(int[], Comparator). To sort an int[] in descending order, sort it ascending and then reverse it, or use a boxed Integer[] (slower), or a stream: IntStream.of(a).boxed().sorted(Comparator.reverseOrder()).

For very large arrays, Arrays.parallelSort splits the work across CPU cores. It only pays off for big arrays (hundreds of thousands of elements); for small ones, plain sort is just as fast.

Searching a sorted array: binarySearch

Arrays.binarySearch(array, key) finds a value in a sorted array by repeatedly halving the range it looks at. A million-element array needs about 20 comparisons instead of up to a million. It returns:

  • the index of the key if it's found, or
  • a negative number if it isn't: -(insertionPoint) - 1, where insertionPoint is the index where the key would go to keep the array sorted.
Java binarySearch and the insertion point

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The - 1 in the formula exists so that "not found, would go at index 0" (-1) can't be confused with "found at index 0" (0). Any negative result means "not found".

binarySearch on an unsorted array doesn't throw; it just returns a wrong answer, as the last line shows (42 is the first element, but the search reports it missing). Sort first, and if you sorted with a comparator, pass the same comparator to binarySearch. If the array contains duplicates, you get the index of one of them, not necessarily the first.

Filling: fill and setAll

Arrays.fill sets every element (or a range) to one value. Arrays.setAll computes each element from its index:

Java
int[] counters = new int[5];
Arrays.fill(counters, -1);                 // [-1, -1, -1, -1, -1]
Arrays.fill(counters, 1, 3, 0);            // [-1, 0, 0, -1, -1]

char[] line = new char[20];
Arrays.fill(line, '=');
String ruler = new String(line);           // "===================="

int[] squares = new int[6];
Arrays.setAll(squares, i -> i * i);        // [0, 1, 4, 9, 16, 25]

i -> i * i is a lambda: "given index i, the element is i * i" (Lambda Expressions). With objects, remember that fill stores the same reference everywhere. Arrays.fill(rows, new int[3]) gives you one shared row, while Arrays.setAll(rows, i -> new int[3]) creates a separate row for each index.

Parallel variants: parallelSetAll and parallelPrefix

For large arrays, Arrays.parallelSetAll does the same job as setAll but splits the index range across the common fork/join pool (Fork/Join). The generator function must be independent per index (no shared mutable state), otherwise the result is unpredictable. Arrays.parallelPrefix(array, op) turns an array into its running totals (a prefix scan): element i becomes the combination of elements 0 to i using an associative operation. For short arrays the sequential setAll is faster, because starting parallel work has a fixed cost.

Java setAll, parallelSetAll and parallelPrefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Copying: copyOf and copyOfRange

Covered in Looping Through Arrays; here's the quick recap:

Java
int[] data = { 1, 2, 3, 4, 5 };
Arrays.copyOf(data, 3);          // [1, 2, 3]           (truncated)
Arrays.copyOf(data, 7);          // [1, 2, 3, 4, 5, 0, 0] (padded)
Arrays.copyOfRange(data, 1, 4);  // [2, 3, 4]

copyOf with a larger length is the standard way to "grow" an array: you make a bigger copy and use it instead. That's exactly what ArrayList does internally when it runs out of room.

Comparing: equals, deepEquals, mismatch and compare

Arrays inherit equals and hashCode from Object, which compare identity. The Arrays class provides content-based versions:

Java Four ways to compare arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  • Arrays.equals(a, b) is true when both arrays have the same length and equal elements in the same order. For object arrays it calls each element's equals.
  • Arrays.deepEquals is the version for nested arrays. Arrays.equals on 2D arrays compares the row references, so it says false above.
  • Arrays.hashCode / Arrays.deepHashCode give content-based hash codes, which you need if an array is part of a class's hashCode (The Object Class).
  • Arrays.mismatch(a, b) (Java 9+) returns the first index where the arrays differ, or -1 if they're equal. If one array is a prefix of the other, it returns the shorter length.
  • Arrays.compare(a, b) (Java 9+) compares arrays lexicographically, like words in a dictionary: the first differing element decides, and a shorter array that is a prefix of a longer one comes first. It returns a negative number, zero or a positive number. Don't rely on the exact value, only on the sign.

Arrays.asList and its pitfalls

Arrays.asList(...) wraps an array in a List view, which is handy for printing and for APIs that want a List. But it has three surprises, and all three show up in real bugs:

Java Three asList surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

  1. It's a view, not a copy. The list and the array share storage, so changing one changes the other.
  2. It's fixed-size. set works, but add, remove and clear throw UnsupportedOperationException, because the array underneath can't change length.
  3. Primitive arrays don't spread out. asList takes a variable number of objects (see Varargs). An int[] is one object, so you get a List<int[]> with a single element, not a list of three numbers.

The fixes are shown at the end: wrap the view in new ArrayList<>(...) for a list that can grow, and use Arrays.stream(...).boxed().toList() to turn primitives into a List<Integer>.

For fixed lists of values, List.of("red", "green", "blue") is often better than asList: it's fully immutable (even set throws) and rejects null. Immutable Collections and Utility Methods compares them.

Streams from arrays

Arrays.stream(array) turns an array into a stream so you can filter, transform and summarize it in one expression. For int[], long[] and double[] you get a specialized stream with sum, average, min and max:

Java Arrays.stream in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

average() returns an OptionalDouble because an empty array has no average; orElse(0) supplies a fallback. Streams get a full chapter starting with Streams; for now, it's enough to know that Arrays.stream is the doorway.

Quick reference

Method Purpose
toString(a) / deepToString(a) readable text of an array / nested arrays
sort(a), sort(a, from, to), sort(a, comparator) sort in place, stable for objects
parallelSort(a) multi-core sort for very large arrays
binarySearch(a, key) index in a sorted array, or -(insertionPoint) - 1
fill(a, value), setAll(a, i -> ...) set every element
copyOf(a, len), copyOfRange(a, from, to) new, resized or partial copies
equals, deepEquals, hashCode, deepHashCode content-based comparison and hashing
mismatch(a, b), compare(a, b) first differing index; lexicographic order
asList(...) fixed-size list view of an object array
stream(a), stream(a, from, to) a stream over the array or a range

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? String[] s = {"b", "C", "a"}; Arrays.sort(s); IO.println(Arrays.toString(s));

    Strings sort by Unicode value, and every uppercase letter comes before every lowercase letter. Use String.CASE_INSENSITIVE_ORDER to ignore case.
  2. 2. In the sorted array {2, 4, 6, 8}, what does Arrays.binarySearch(a, 5) return?

    5 would be inserted at index 2, so the result is -(2) - 1 = -3. Any negative result means the key was not found.
  3. 3. What is Arrays.asList(new int[] {1, 2, 3}).size()?

    asList takes objects, and the whole int[] is a single object, so the result is a List<int[]> with one element. Use Arrays.stream(a).boxed().toList() instead.
  4. 4. What happens? List<String> list = Arrays.asList("x", "y"); list.add("z");

    The list returned by asList is a fixed-size view of an array. set works, but add and remove throw. Copy it into new ArrayList<>(...) if you need to grow it.
  5. 5. What does Arrays.mismatch(new int[] {5, 6, 7}, new int[] {5, 6, 8}) return?

    mismatch returns the first index where the arrays differ. Indexes 0 and 1 match, and index 2 holds 7 vs 8. It returns -1 only when the arrays are equal.

Summary

  • java.util.Arrays is a class of static helpers; you call them as Arrays.method(array).
  • toString/deepToString print arrays; sort sorts in place (stable for objects) and accepts ranges and comparators for object arrays.
  • binarySearch needs a sorted array and returns -(insertionPoint) - 1 when the key is missing.
  • fill sets one value everywhere (one shared reference for objects); setAll computes each element from its index.
  • equals/deepEquals and hashCode/deepHashCode compare contents; mismatch finds the first difference and compare orders arrays lexicographically.
  • asList returns a fixed-size view that writes through to the array and treats a primitive array as one element; copy it into an ArrayList or use List.of instead.
  • Arrays.stream opens arrays to the Streams API, with sum, average, filter and more.

Next: Methods, where you'll package code into named, reusable pieces, just like the methods of the Arrays class.