
In Java, an array is a sequence of values of the same type with a fixed length. You access the values via an index, and the index starts at 0.
The following program creates an array with five numbers, prints the element at index 2, changes it, and then prints the whole array:
int[] numbers = {3, 1, 4, 1, 5};
System.out.println(numbers[2]);
numbers[2] = 9;
System.out.println(Arrays.toString(numbers));
4
[3, 1, 9, 1, 5]
For the last line, you need Arrays.toString() from the class java.util.Arrays. Without it, System.out.println(numbers) does not print the elements, but only something like [I@2b2fa4f7 – the class name of the array and its hash code. For sorting, searching, comparing, and printing, you need the static methods of the Arrays class, because an array itself has no methods for that.
In this article, you will learn
- what an array is and how to create, read, change, and iterate over it,
- which methods the
Arraysclass has and how to use them to print, sort, search, compare, fill, and copy an array, - how to append or remove an element even though an array cannot change its length – and what that costs,
- how to convert arrays into lists and back, and which trap
Arrays.asList()sets with anint[], - when to use an array and when an
ArrayList, - how an array works internally: as an object, as a class of its own, and with a check on every write,
- which mistakes are the most common with arrays.
The Examples in This Article
You can find the complete code in the GitHub repository java-arrays, in the package eu.happycoders.basics. Each section has its own class there, with a main() method that produces the outputs shown. The benchmarks are in the subpackage benchmark.
The classes in the repository need Java 25 because they use the simplified main() method without String[] args. The listings in the article run on Java 16 and later: records and Stream.toList(), the most recent language features and methods in them, have existed since Java 16.
What Is an Array?
An array stores a fixed number of elements of the same type. The elements are numbered from 0: an array with five elements has the indexes 0 to 4.
In Java, an array is an object. It lives on the heap, and a variable of type int[] does not contain the array itself, but a reference to it. The following diagram shows the variable numbers from the first example and the array it points to:
Two properties of an array come up again and again in this article.
First, the array cannot change its length. You set it when you create the array, and after that, it stays as it is. The section Appending, Removing, Reversing shows how you can still append an element.
Second, two variables can point to the same array. The following listing assigns the array from a to the variable b and then changes the first element via b:
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
System.out.println("a = " + Arrays.toString(a));
System.out.println("b = " + Arrays.toString(b));
a = [99, 2, 3]
b = [99, 2, 3]
The assignment b = a did not create a second array; it only copied the reference – that’s why you also see the change made via b in a. The section Filling and Copying Arrays shows how to really copy an array.
An array can contain primitive values or references to objects. An int[] stores the numbers themselves and therefore cannot contain null. A String[], on the other hand, stores references to String objects – and an array element to which you have not yet assigned a string contains null:
String[] names = new String[3];
names[0] = "Ada";
names[1] = "Linus";
System.out.println("names = " + Arrays.toString(names));
names = [Ada, Linus, null]
The following diagram shows this String[] above the int[] from the first example. The elements of the String[] point to the two String objects; the third points to nothing. The int[] contains the numbers themselves:
Creating an Array
You create an array in one of three ways:
- With
new, the type, and a length in square brackets, you get an array whose elements have their default value. - Without the length in the square brackets, but with a list of values in curly braces, you get an array with exactly these values.
- If you create the array right in the declaration of the variable, you may also omit
new int[].
The following listing shows the three ways one after the other:
// Way 1: new with a length – the elements have their default value
int[] zeros = new int[5];
String[] names = new String[3];
boolean[] flags = new boolean[2];
// Way 2: new with a list of values
int[] primes = new int[] {2, 3, 5, 7, 11};
// Way 3: only the values, right in the declaration
int[] squares = {1, 4, 9, 16, 25};
System.out.println("zeros = " + Arrays.toString(zeros));
System.out.println("names = " + Arrays.toString(names));
System.out.println("flags = " + Arrays.toString(flags));
System.out.println("primes = " + Arrays.toString(primes));
System.out.println("squares = " + Arrays.toString(squares));
zeros = [0, 0, 0, 0, 0]
names = [null, null, null]
flags = [false, false]
primes = [2, 3, 5, 7, 11]
squares = [1, 4, 9, 16, 25]
The default value is 0 for all numeric types, false for boolean, the character '\u0000' for char, and null for all reference types.
The article How to Initialize an Array in Java shows how to declare and initialize an array, why int numbers[] compiles but is not recommended, and how to create an empty array.
Reading and Changing Elements
You read an element with its index in square brackets, and with the same notation to the left of the equals sign, you change it. The last element has the index length - 1:
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]);
System.out.println(numbers[numbers.length - 1]);
numbers[1] = 21;
System.out.println(Arrays.toString(numbers));
10
50
[10, 21, 30, 40, 50]
An index outside 0 to length - 1 compiles, but throws an ArrayIndexOutOfBoundsException at runtime. The following listing accesses index 5 and index −1 of the same array and prints the two exceptions:
int[] numbers = {10, 20, 30, 40, 50};
try {
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
try {
System.out.println(numbers[-1]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e);
}
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5
The message names the index and the length of the array. If the index in the message equals the length, a loop with <= instead of < in its condition is often behind it – a so-called off-by-one error.
An object array has a second exception in store. An element to which you have not yet assigned anything is null, and a method call on it throws a NullPointerException:
String[] names = new String[3];
try {
System.out.println(names[0].toUpperCase());
} catch (NullPointerException e) {
System.out.println(e);
}
java.lang.NullPointerException: Cannot invoke "String.toUpperCase()" because "names[0]" is null
The message names the expression that was null – here, the element names[0]. These so-called Helpful NullPointerExceptions came with Java 14 and have been enabled by default since Java 15.
The Length of an Array
The length of an array is in its field length. It is a field, not a method – so you write it without parentheses. A String, on the other hand, has the method length(), and a list has the method size():
int[] numbers = {10, 20, 30};
String text = "Hello";
List<Integer> list = List.of(10, 20, 30, 40);
System.out.println(numbers.length);
System.out.println(text.length());
System.out.println(list.size());
3
5
4
You set the length when you create the array; after that, it cannot change. The article Array Length in Java shows how to determine the length of a 2D array, how much memory an array takes up, and how large an array can get.
Iterating Over an Array
The classic way to iterate over an array is the counting loop with an index from 0 to length - 1:
int[] numbers = {4, 8, 15, 16, 23, 42};
for (int i = 0; i < numbers.length; i++) {
System.out.println(i + ": " + numbers[i]);
}
0: 4
1: 8
2: 15
3: 16
4: 23
5: 42
If you don’t need the index, the for-each loop is shorter. The following listing uses it to calculate the sum and the maximum of the numbers:
int[] numbers = {4, 8, 15, 16, 23, 42};
int sum = 0;
int max = Integer.MIN_VALUE;
for (int number : numbers) {
sum += number;
max = Math.max(max, number);
}
System.out.println("sum = " + sum + ", max = " + max);
sum = 108, max = 42
There is one thing the for-each loop cannot do, though: change the array. Its loop variable is a copy of the element, and an assignment to it changes only that copy. The following listing tries to double all numbers – first with the for-each loop, then with the counting loop:
int[] numbers = {4, 8, 15, 16, 23, 42};
for (int number : numbers) {
number = number * 2; // changes only the loop variable
}
System.out.println("after for-each: " + Arrays.toString(numbers));
for (int i = 0; i < numbers.length; i++) {
numbers[i] = numbers[i] * 2;
}
System.out.println("after index loop: " + Arrays.toString(numbers));
after for-each: [4, 8, 15, 16, 23, 42]
after index loop: [8, 16, 30, 32, 46, 84]
To run backwards, you start the counting loop at the last index:
int[] numbers = {4, 8, 15, 16, 23, 42};
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i] + " ");
}
42 23 16 15 8 4
For sum, minimum, and maximum, there is also a way without a loop: Arrays.stream() turns an int[] into an IntStream, and that has the methods sum(), min(), and max():
int[] numbers = {4, 8, 15, 16, 23, 42};
System.out.println("sum = " + Arrays.stream(numbers).sum());
System.out.println("min = " + Arrays.stream(numbers).min().getAsInt());
System.out.println("max = " + Arrays.stream(numbers).max().getAsInt());
sum = 108
min = 4
max = 42
min() and max() return an OptionalInt because an empty array has no minimum – getAsInt() would then throw a NoSuchElementException.
If you need the index in the stream, you create a stream of the indexes with IntStream.range(). The following listing finds the indexes of all multiples of 4:
int[] numbers = {4, 8, 15, 16, 23, 42};
int[] indexes =
IntStream.range(0, numbers.length)
.filter(i -> numbers[i] % 4 == 0)
.toArray();
System.out.println(Arrays.toString(indexes));
[0, 1, 3]
The article Java Streams explains which stream operations there are and how they work.
The Methods of the Arrays Class at a Glance
An array has no methods of its own apart from those it inherits from Object and a public clone() method. In addition, there is the field length. Everything else – printing, sorting, searching, comparing, filling, copying, converting – you do with the static methods of the class java.util.Arrays.
The following table shows all methods, grouped like the following sections. Under “Other” at the end are those that have no section of their own. The “Since” column names the Java version in which a method was added. The class itself has existed since Java 1.2:
| Method | What it does | Since |
|---|---|---|
| Printing | ||
toString(array) | returns the elements as a String, e.g., [3, 1, 4] | Java 5 |
deepToString(array) | the same for nested arrays | Java 5 |
| Sorting | ||
sort(array) | sorts the array in ascending order | Java 1.2 |
sort(array, comparator) | sorts an object array by a Comparator | Java 1.2 |
parallelSort(array) | sorts with multiple threads | Java 8 |
| Searching | ||
binarySearch(array, key) | searches a sorted array | Java 1.2 |
| Comparing | ||
equals(a, b) | compares the contents of two arrays | Java 1.2 |
deepEquals(a, b) | the same for nested arrays | Java 5 |
hashCode(array) | calculates a hash code from the elements | Java 5 |
compare(a, b) | compares two arrays lexicographically | Java 9 |
mismatch(a, b) | returns the first index at which they differ | Java 9 |
| Filling and copying | ||
fill(array, value) | sets all elements to the same value | Java 1.2 |
setAll(array, generator) | calculates each element from its index | Java 8 |
copyOf(array, length) | copies the array into a new one of the given length | Java 6 |
copyOfRange(array, from, to) | copies a range into a new array | Java 6 |
| Converting | ||
asList(array) | returns a List that works on the array | Java 1.2 |
stream(array) | returns a stream of the elements | Java 8 |
| Other | ||
deepHashCode(array) | calculates a hash code for nested arrays | Java 5 |
parallelPrefix(array, op) | replaces each element by its combination with all previous ones, e.g., a running sum, with multiple threads | Java 8 |
parallelSetAll(array, generator) | like setAll(), with multiple threads | Java 8 |
spliterator(array) | returns a Spliterator over the elements | Java 8 |
compareUnsigned(a, b) | like compare(), but treats integers as unsigned | Java 9 |
Almost all methods exist several times: one variant for each primitive type and one for Object[], and many additionally with a range of start and end index. The range variants of binarySearch() were added only with Java 6, those of equals() with Java 9.
Printing an Array
The obvious way would be to print an array directly with System.out.println() – or, as of Java 25, with IO.println(). The following listing tries it with an int[] and a String[]:
int[] numbers = {3, 1, 4};
String[] names = {"Ada", "Linus", "Grace"};
System.out.println(numbers);
System.out.println(names);
[I@4c873330
[Ljava.lang.String;@7ad041f3
Instead of the elements, you see the name of the array class and, after the @, the array’s identity hash code in hexadecimal notation, which has nothing to do with the contents. This is the return value of the toString() method that the array inherits from Object. The section Every Array Type Is a Class explains what [I and [Ljava.lang.String; mean; the identity hash code differs for every object and on every program start.
You get the elements of the array with Arrays.toString():
int[] numbers = {3, 1, 4};
String[] names = {"Ada", "Linus", "Grace"};
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(names));
[3, 1, 4]
[Ada, Linus, Grace]
For a 2D array, that’s not enough. Arrays.toString() prints its elements, and those are arrays again – you can see that in the first line of the output of the following example. For nested arrays, there is Arrays.deepToString():
int[][] matrix = {{1, 2}, {3, 4}};
System.out.println(Arrays.toString(matrix));
System.out.println(Arrays.deepToString(matrix));
[[I@251a69d7, [I@7344699f]
[[1, 2], [3, 4]]
The section Printing a 2D Array of the article on 2D arrays shows how to print a 2D array row by row and with aligned columns.
If you need a format other than the square brackets, you join the elements yourself. For a String[] with a delimiter, String.join() does that. For a prefix and suffix – and for any int[] – you need a stream and Collectors.joining(). The method exists with a delimiter and with a delimiter, prefix, and suffix. You first convert the numbers of an int[] into strings with mapToObj():
int[] numbers = {3, 1, 4};
String[] names = {"Ada", "Linus", "Grace"};
System.out.println(String.join(" | ", names));
System.out.println(
Arrays.stream(names)
.collect(Collectors.joining(", ", "<", ">")));
System.out.println(
Arrays.stream(numbers)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" | ")));
System.out.println(
Arrays.stream(numbers)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ", "<", ">")));
Ada | Linus | Grace
<Ada, Linus, Grace>
3 | 1 | 4
<3, 1, 4>
There is one exception: System.out.println() prints a char[] as text, because System.out is a PrintStream, and that has its own println(char[]) method. This no longer applies, however, as soon as you concatenate the array with a string:
char[] letters = {'J', 'a', 'v', 'a'};
System.out.println(letters);
System.out.println("letters = " + letters);
System.out.println("letters = " + Arrays.toString(letters));
Java
letters = [C@4e25154f
letters = [J, a, v, a]
In the second line, the concatenation calls toString(), and that again returns the class name and hash code.
Sorting an Array
You sort an array with Arrays.sort(). The method sorts the array in place and returns nothing:
int[] numbers = {5, 3, 8, 1};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers));
[1, 3, 5, 8]
Arrays.sort() sorts strings by their natural order, which compares them character by character by Unicode value. Uppercase letters therefore come before lowercase letters. With a Comparator as the second argument, you can sort differently, in the following example without regard to upper and lower case:
String[] names = {"Linus", "ada", "Grace"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
Arrays.sort(names, String.CASE_INSENSITIVE_ORDER);
System.out.println(Arrays.toString(names));
[Grace, Linus, ada]
[ada, Grace, Linus]
You sort in descending order with Comparator.reverseOrder(). That only works with an object array, though, i.e., with Integer[] instead of int[] – there is no sort() variant with a Comparator for primitive arrays:
Integer[] boxed = {5, 3, 8, 1};
Arrays.sort(boxed, Comparator.reverseOrder());
System.out.println(Arrays.toString(boxed));
[8, 5, 3, 1]
The article Sorting in Java shows how to sort a primitive int[] in descending order anyway, which algorithms are behind Arrays.sort(), and when Arrays.parallelSort() pays off.
Searching an Array
An array has no contains() and no indexOf() method, and neither does the Arrays class. For an int[], the easiest way is to write the two yourself:
static boolean contains(int[] array, int value) {
for (int element : array) {
if (element == value) {
return true;
}
}
return false;
}
static int indexOf(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return i;
}
}
return -1;
}
Without a method of your own, you can use a stream and anyMatch(). The following listing checks once with contains() and once with anyMatch() whether 15 is in the array, and then uses indexOf() to find the index of 23 and of 7:
int[] numbers = {4, 8, 15, 16, 23, 42};
System.out.println(contains(numbers, 15));
System.out.println(Arrays.stream(numbers).anyMatch(n -> n == 15));
System.out.println(indexOf(numbers, 23));
System.out.println(indexOf(numbers, 7));
true
true
4
-1
You can turn an object array into a list with Arrays.asList() and then call the list’s methods contains() and indexOf(). Arrays.asList() copies nothing – the section Arrays and Lists shows how the list works:
String[] names = {"Ada", "Linus", "Grace"};
System.out.println(Arrays.asList(names).contains("Grace"));
System.out.println(Arrays.asList(names).indexOf("Grace"));
true
2
This does not work for an int[]. The following call compiles, but returns false, although 15 is in the array:
int[] numbers = {4, 8, 15, 16, 23, 42};
System.out.println(Arrays.asList(numbers).contains(15));
false
Here, Arrays.asList(numbers) returns a List<int[]> with a single element – the array itself. The section The int[] Trap explains why.
What the Three Ways Cost
I measured how fast the three ways are with JMH. The benchmark ContainsBenchmark searches for a value that is not in the array – so each way has to look at all elements. In the int[], it searches with the loop and with anyMatch(); in the String[], additionally with Arrays.asList().contains(). The first table shows the time for one search in the int[]:
| Elements | Loop | anyMatch() |
|---|---|---|
| 100 | 11 ns | 72 ns |
| 10,000 | 1.0 µs | 6.5 µs |
| 1,000,000 | 104 µs | 453 µs |
In the int[], the stream takes 4.4 to 6.5 times as long as the loop – 453 instead of 104 µs for one million elements.
The second table shows the search in the String[]:
| Elements | Loop | asList().contains() | anyMatch() |
|---|---|---|---|
| 100 | 52 ns | 57 ns | 86 ns |
| 10,000 | 4.7 µs | 5.8 µs | 11.2 µs |
| 1,000,000 | 588 µs | 598 µs | 790 µs |
Arrays.asList().contains() is at most a quarter slower than your own loop; the stream takes 1.3 to 2.4 times as long as the loop.
For the int[], the factor between loop and anyMatch() was much larger. The reason: the loop compares two int values directly in the array. For a string comparison, on the other hand, each way calls equals(), and that first loads the string object for each element and then its internal byte[]. This effort is the same for all three ways, and the additional overhead of the stream carries less weight next to it.
For a String[], I therefore recommend Arrays.asList().contains() – short and hardly slower than the loop. For an int[], your own contains() method pays off if you search often. And if you search the same data very often, there are two faster ways: you sort the array once and then search it with binary search in O(log n), or you put the elements into a HashSet – that finds an element in O(1).
Binary Search
In a sorted array, you find an element faster with binary search than with a loop over all elements: Arrays.binarySearch() halves the search range with every step and needs at most 20 comparisons for one million elements. The method returns the index of the element found. If the element is missing, it returns a negative number: −(insertion point) − 1, where the insertion point is the index at which the element would have to be:
int[] numbers = {4, 8, 15, 16, 23, 42};
System.out.println(Arrays.binarySearch(numbers, 16));
System.out.println(Arrays.binarySearch(numbers, 10));
3
-3
The method finds 16 at index 3. The 10 would have to be between 8 and 15, i.e., at index 2. That results in −2 − 1 = −3.
On an unsorted array, the result is undefined according to the Javadoc. The following listing searches for 42, which is at the first position in the array:
int[] unsorted = {42, 4, 23, 8, 16, 15};
System.out.println(Arrays.binarySearch(unsorted, 42));
-7
The binary search did not find 42. Its first comparison hit 23 in the middle, and because 42 is greater, it only searched to the right of it – where the greater values are in a sorted array.
The article Binary Search in Java explains how binary search works and from which array size it beats linear search.
Comparing Arrays
Two arrays with the same contents are not equal for ==, because == compares the references. equals() doesn’t help either: an array inherits the method from Object, and that also compares the references. Only Arrays.equals() compares the contents:
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println("a == b : " + (a == b));
System.out.println("a.equals(b) : " + a.equals(b));
System.out.println("Arrays.equals(a, b) : " + Arrays.equals(a, b));
a == b : false
a.equals(b) : false
Arrays.equals(a, b) : true
With nested arrays, Arrays.equals() again compares the inner arrays only by reference – and in the following example, those are arrays with the same contents, but different objects nonetheless. For nested arrays, there is Arrays.deepEquals():
int[][] m1 = {{1, 2}, {3, 4}};
int[][] m2 = {{1, 2}, {3, 4}};
System.out.println("Arrays.equals(m1, m2) : " + Arrays.equals(m1, m2));
System.out.println("Arrays.deepEquals(m1, m2) : " + Arrays.deepEquals(m1, m2));
Arrays.equals(m1, m2) : false
Arrays.deepEquals(m1, m2) : true
Arrays as Keys and in Records
What applies to equals() also applies to hashCode(): the method inherited from Object returns the identity hash code of the object. Only Arrays.hashCode() gives you a hash code that is the same for two arrays with the same contents.
The inherited methods become a problem as soon as an array is a key in a HashMap or a component of a record:
record Point(int[] coordinates) {}
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
Map<int[], String> map = new HashMap<>();
map.put(a, "found");
System.out.println("map.get(a) = " + map.get(a));
System.out.println("map.get(b) = " + map.get(b));
System.out.println(new Point(a).equals(new Point(b)));
map.get(a) = found
map.get(b) = null
false
Because the HashMap compares keys via hashCode() and equals(), it finds the entry only with the same array object a, not with b, which has the same contents. And two Point records with arrays of the same contents are not equal, because the generated equals() of a record compares each component with Objects.equals() – and for an array, that calls the array’s inherited equals(), which again compares only the references.
As the key of a map, you are therefore better off with a List<Integer> or a record with individual fields. If you absolutely need an array in a record, you have to override equals(), hashCode(), and toString() in that record and call the matching methods of the Arrays class in them.
compare() and mismatch()
Since Java 9, there are two more comparison methods. Arrays.compare() compares two arrays lexicographically, i.e., element by element like words in a dictionary, and returns a number – negative if the first array belongs before the second, 0 if both are equal, and positive if the first belongs after the second. Arrays.mismatch() returns the first index at which two arrays differ, or −1 if they are equal:
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.compare(a, new int[] {1, 2, 4}));
System.out.println(Arrays.compare(a, new int[] {1, 2}));
System.out.println(Arrays.mismatch(a, new int[] {1, 2, 4}));
System.out.println(Arrays.mismatch(a, b));
-1
1
2
-1
{1, 2, 3} is less than {1, 2, 4} because 3 is less than 4, and greater than {1, 2} because it is longer and matches at the beginning.
Arrays.equals() or Your Own Loop?
Arrays.equals() is faster than a loop that compares two arrays element by element. How much faster depends on the element type. The benchmark EqualsBenchmark compares two arrays with the same contents once with Arrays.equals() and once with a loop that stops at the first difference – for int[] and for byte[]. The table shows the time for one comparison:
| Elements | int[]Arrays.equals() | int[]loop | byte[]Arrays.equals() | byte[]loop |
|---|---|---|---|---|
| 10 | 1.8 ns | 2.3 ns | 1.0 ns | 2.2 ns |
| 100 | 8.5 ns | 14 ns | 3.0 ns | 15 ns |
| 10,000 | 740 ns | 1.3 µs | 127 ns | 1.5 µs |
| 1,000,000 | 84 µs | 130 µs | 15 µs | 147 µs |
For int[], from 100 elements on, the loop takes 1.5 to 1.8 times as long as Arrays.equals(); for byte[], up to 11.5 times as long.
The difference comes from how the JVM executes the two methods. For byte[] (and also char[]), Arrays.equals() is a so-called intrinsic: the JIT compiler replaces the call with its own machine code that compares several bytes at once, and for longer arrays uses the CPU’s SIMD instructions – that’s where the speedup of up to 11.5 times comes from.
For int[] and the other types, Arrays.equals() calls the method ArraysSupport.vectorizedMismatch(). On x86 processors, it is an intrinsic, too. On ARM processors such as the Apple M5 I measured on, however, the JVM runs its Java code – and that always reads 8 bytes at once, i.e., compares two int values in one step. This does not make the comparison twice as fast, but with a factor of up to 1.8, almost.
So there is no reason to write your own loop for comparing two arrays: Arrays.equals() is shorter and was faster in all measured cases.
Filling and Copying Arrays
Arrays.fill() sets all elements of an array to the same value, in the following example to 7. Arrays.setAll() calculates each element from its index with a function, in the example the square of the index:
int[] numbers = new int[5];
Arrays.fill(numbers, 7);
System.out.println(Arrays.toString(numbers));
Arrays.setAll(numbers, i -> i * i);
System.out.println(Arrays.toString(numbers));
[7, 7, 7, 7, 7]
[0, 1, 4, 9, 16]
There are four ways to copy an array. The following table shows what each one is meant for:
| Way | What for |
|---|---|
array.clone() | a copy of the whole array |
Arrays.copyOf(array, length) | a copy with a different length – shorter truncates, longer pads with default values |
Arrays.copyOfRange(array, from, to) | a copy of a range, to exclusive |
System.arraycopy(src, srcPos, dest, destPos, length) | copying into an array that already exists |
The following listing applies all four methods to the array {0, 1, 4, 9, 16}:
int[] numbers = {0, 1, 4, 9, 16};
int[] clone = numbers.clone();
int[] shorter = Arrays.copyOf(numbers, 3);
int[] longer = Arrays.copyOf(numbers, 7);
int[] range = Arrays.copyOfRange(numbers, 1, 4);
int[] target = new int[7];
System.arraycopy(numbers, 0, target, 2, 5);
System.out.println("clone = " + Arrays.toString(clone));
System.out.println("shorter = " + Arrays.toString(shorter));
System.out.println("longer = " + Arrays.toString(longer));
System.out.println("range = " + Arrays.toString(range));
System.out.println("target = " + Arrays.toString(target));
clone = [0, 1, 4, 9, 16]
shorter = [0, 1, 4]
longer = [0, 1, 4, 9, 16, 0, 0]
range = [1, 4, 9]
target = [0, 0, 0, 1, 4, 9, 16]
System.arraycopy() is – like Arrays.equals() for byte[] – an intrinsic: the JIT compiler replaces the call with a ready-made copy routine of the JVM. It checks indexes and length once at the beginning instead of for each element and then copies whole blocks. On the Apple M5, it reads and writes 16 bytes per instruction, i.e., four int values at once, and fetches the following bytes into the CPU cache in advance. If the source and target ranges overlap in the same array, the method copies from back to front so that it does not overwrite elements it still has to read.
Arrays.copyOf() and Arrays.copyOfRange() call System.arraycopy() internally and therefore use the same efficient copy routine.
All four ways copy the elements – for an object array, that means the references, not the objects. The original array and the copy then point to the same objects. The following listing copies an array containing a StringBuilder and appends text via the copy:
StringBuilder[] original = {new StringBuilder("Ada")};
StringBuilder[] copy = original.clone();
copy[0].append(" Lovelace");
System.out.println("original[0] = " + original[0]);
original[0] = Ada Lovelace
The change made via copy is also visible in original, because both arrays point to the same StringBuilder. Such a shallow copy becomes a problem if you want to change the objects in the copy without changing the original. For that, you need a deep copy, which also copies the objects themselves.
With arrays of strings, the shallow copy is not a problem: strings are immutable, so you cannot change a string via the copy. You can only replace an element of the copy with another string, e.g., with copy[0] = "Grace". Then only the copy points to the new string; original[0] still points to the old string.
The sections Filling an Array With Values and How to Copy a Java Array of the article on initializing arrays cover the variants of fill() and setAll(), deep copies, and which way is the fastest.
Appending, Removing, Reversing: What an Array Cannot Do
An array cannot grow and cannot shrink. Appending or removing an element therefore always means: creating a new array and copying the elements into it.
Appending an Element
You append an element by creating an array that is one longer with Arrays.copyOf() and writing the new element to the last index:
int[] numbers = {1, 2, 3};
numbers = Arrays.copyOf(numbers, numbers.length + 1);
numbers[numbers.length - 1] = 4;
System.out.println(Arrays.toString(numbers));
[1, 2, 3, 4]
For a single element, that’s fine. In a loop, it gets expensive: each append copies all previous elements, and for n elements, that adds up to n · (n − 1) / 2 copy operations. The running time grows quadratically with n.
An ArrayList avoids that: it does not grow its internal array by one, but by half of its previous size, and therefore rarely has to copy. The section How the ArrayList Grows of the ArrayList article shows exactly how that works.
The benchmark AppendBenchmark shows how big the difference is. It appends n numbers one by one – to an array with Arrays.copyOf() per element, to an ArrayList<Integer>, and to an int[] that, like the ArrayList, grows by half as soon as it is full. So the last one does the same as the ArrayList, only without converting to Integer objects. The table shows the time for all n elements together:
| Elements | Arrays.copyOf()per element | ArrayList<Integer> | int[] growingby half |
|---|---|---|---|
| 1,000 | 36 µs | 2.5 µs | 0.69 µs |
| 10,000 | 5.2 ms | 28 µs | 7.7 µs |
| 100,000 | 350 ms | 254 µs | 66 µs |
Ten times as many elements cost 67 to 144 times as much time with Arrays.copyOf() per element – quadratic growth, as expected. With the ArrayList and the growing int[], on the other hand, the time grows linearly with n. With 100,000 elements, Arrays.copyOf() per element therefore takes about 1,400 times as long as the ArrayList: 350 ms instead of 0.25 ms.
The growing int[] is another 3.6 to 3.9 times as fast as the ArrayList. Since both grow the same way, this difference comes from converting each number into an Integer object, the so-called boxing. For most programs, the ArrayList is still the right choice. A class of your own with an int[] only pays off when your profiler shows the boxing when writing to the list, or the unboxing when reading from it – the conversion back to an int – as a hotspot.
Removing an Element
You remove an element by creating an array that is one shorter and copying the elements before and after the gap into it with System.arraycopy():
static int[] remove(int[] array, int index) {
int[] result = new int[array.length - 1];
System.arraycopy(array, 0, result, 0, index);
System.arraycopy(array, index + 1, result, index, array.length - index - 1);
return result;
}
The following listing removes the element at index 1 from {1, 2, 3, 4}:
int[] numbers = {1, 2, 3, 4};
numbers = remove(numbers, 1);
System.out.println(Arrays.toString(numbers));
[1, 3, 4]
The code also works if you remove the first or the last element. Then one of the two System.arraycopy() calls has 0 elements to copy – it does not fail, it simply does nothing.
Concatenating Two Arrays
You concatenate two arrays following the same principle: Arrays.copyOf() creates an array with the sum of both lengths and copies the first one into it, and System.arraycopy() copies the second one behind it. For an int[], IntStream.concat() works, too:
int[] first = {1, 2};
int[] second = {3, 4, 5};
int[] both = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, both, first.length, second.length);
System.out.println(Arrays.toString(both));
int[] viaStream =
IntStream.concat(Arrays.stream(first), Arrays.stream(second))
.toArray();
System.out.println(Arrays.toString(viaStream));
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
Reversing an Array
There is no Arrays.reverse() method. You reverse an array by swapping the elements in pairs from both ends until the two indexes meet in the middle:
static void reverse(int[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
The following listing reverses an array of five numbers:
int[] numbers = {1, 2, 3, 4, 5};
reverse(numbers);
System.out.println(Arrays.toString(numbers));
[5, 4, 3, 2, 1]
You can also reverse an object array with Collections.reverse(Arrays.asList(array)) – the list from Arrays.asList() writes its changes through to the array. With an int[], on the other hand, nothing happens, and the compiler doesn’t warn you:
Integer[] boxed = {1, 2, 3};
Collections.reverse(Arrays.asList(boxed));
System.out.println(Arrays.toString(boxed));
int[] primitives = {1, 2, 3};
Collections.reverse(Arrays.asList(primitives));
System.out.println(Arrays.toString(primitives));
[3, 2, 1]
[1, 2, 3]
The following section explains the second line.
Arrays and Lists
You often convert arrays and lists into each other: many APIs expect a List, others return an array – and vice versa. There are several ways to do this, and they differ in whether you get a copy or a view of the array.
Arrays.asList(): A View of the Array
Arrays.asList() does not copy the array. The method returns a so-called view – a list that works on the array. The following diagram shows the list view and the array names it accesses:
A change via the list is therefore visible in the array and vice versa. But the list cannot change its size, because the array cannot – add() and remove() throw an UnsupportedOperationException:
String[] names = {"Ada", "Linus", "Grace"};
List<String> view = Arrays.asList(names);
view.set(0, "Alan");
System.out.println("names = " + Arrays.toString(names));
names[1] = "Barbara";
System.out.println("view = " + view);
try {
view.add("Ken");
} catch (UnsupportedOperationException e) {
System.out.println(e);
}
names = [Alan, Linus, Grace]
view = [Alan, Barbara, Grace]
java.lang.UnsupportedOperationException
A view is handy if you want to apply a method like contains() or Collections.reverse() to an array without copying it. You should not keep the view for long, though: otherwise, anyone who still holds a reference to the array changes the list without you noticing.
The int[] Trap
Arrays.asList() is a method with a type parameter T and a varargs parameter T... a. A String[] fits that: T becomes String, and the array becomes the varargs array. An int[], however, does not fit, because T cannot be a primitive type. What T can be is an array of a primitive type. The compiler therefore makes T an int[] and passes the array as the only element:
int[] numbers = {1, 2, 3};
List<int[]> wrong = Arrays.asList(numbers);
System.out.println("wrong = " + wrong);
System.out.println("wrong.size() = " + wrong.size());
wrong = [[I@251a69d7]
wrong.size() = 1
The list contains a single element – the array itself, which println() again prints as class name and hash code.
To convert the int[] into a list of numbers, you can go via a stream: Arrays.stream() returns an IntStream, boxed() turns it into a Stream<Integer>, and toList() collects it into an unmodifiable list:
int[] numbers = {1, 2, 3};
List<Integer> right = Arrays.stream(numbers).boxed().toList();
System.out.println("right = " + right);
System.out.println("right.size() = " + right.size());
right = [1, 2, 3]
right.size() = 3
An Independent List
If you need a list that is independent of the array – whose changes are not visible in the array and vice versa – you have two options:
- With
new ArrayList<>(Arrays.asList(array)), you can copy theListview of the array into anArrayList, which you can then change as you like. - Since Java 9, you can copy the elements into an unmodifiable list with
List.of().
The following listing creates both lists, then changes the array and the ArrayList, and finally tries to change the unmodifiable list:
String[] names = {"Ada", "Linus", "Grace"};
List<String> copy = List.of(names);
List<String> growable = new ArrayList<>(Arrays.asList(names));
names[0] = "Edsger";
growable.add("Ken");
System.out.println("names = " + Arrays.toString(names));
System.out.println("copy = " + copy);
System.out.println("growable = " + growable);
try {
copy.set(0, "Ken");
} catch (UnsupportedOperationException e) {
System.out.println(e);
}
names = [Edsger, Linus, Grace]
copy = [Ada, Linus, Grace]
growable = [Ada, Linus, Grace, Ken]
java.lang.UnsupportedOperationException
The assignment names[0] = "Edsger" changes neither of the two lists – both have their own copy of the elements. And only the ArrayList lets you add an element.
By the way, List.of() throws a NullPointerException if an element is null – Arrays.asList() and ArrayList allow null. The section Converting an Array Into an ArrayList of the ArrayList article covers more on converting to an ArrayList.
From the List Back to an Array
You convert a list back into an array with toArray(). With the method reference String[]::new as the argument, you get an array of the right type. A List<Integer> becomes an Integer[] via toArray() – if you need an int[], you use a stream again:
List<String> names = List.of("Ada", "Linus", "Grace");
String[] array = names.toArray(String[]::new);
System.out.println(Arrays.toString(array));
List<Integer> numbers = List.of(1, 2, 3);
Integer[] boxed = numbers.toArray(Integer[]::new);
System.out.println(Arrays.toString(boxed));
int[] ints = numbers.stream().mapToInt(Integer::intValue).toArray();
System.out.println(Arrays.toString(ints));
[Ada, Linus, Grace]
[1, 2, 3]
[1, 2, 3]
The section How to Convert a List to an Array of the article on initializing arrays shows which toArray() variants there are and which one is the fastest.
By the way, you cannot create an array of lists like List<String>[] with new List<String>[3]. The section Why There Are No Generic Arrays explains why. A List<List<String>> is the better choice in this case.
Arrays as Parameters and Return Values
When you pass an array to a method, the method gets a copy of the reference – not a copy of the array. If the method changes an element in this array, the caller of the method sees this change, too. If, on the other hand, the method assigns a new array to the parameter, that changes only its copy of the reference – the caller sees nothing of it:
static void doubleAll(int[] values) {
for (int i = 0; i < values.length; i++) {
values[i] *= 2;
}
}
static void replace(int[] values) {
values = new int[] {0, 0, 0};
System.out.println("values = " + Arrays.toString(values));
}
The following listing calls both methods with the same array:
int[] numbers = {1, 2, 3};
System.out.println("numbers = " + Arrays.toString(numbers));
doubleAll(numbers);
System.out.println("numbers = " + Arrays.toString(numbers));
replace(numbers);
System.out.println("numbers = " + Arrays.toString(numbers));
numbers = [1, 2, 3]
numbers = [2, 4, 6]
values = [0, 0, 0]
numbers = [2, 4, 6]
doubleAll() doubled the elements of the array. In replace(), values does point to the new array, but the method did not change the caller’s array.
A method can also return an array. If it finds nothing, it is best to return an empty array instead of null – then the caller can iterate over it without a check. The method evens() in the following listing returns the even numbers of an array, range() the numbers from from up to but excluding to:
static int[] range(int from, int to) {
int[] result = new int[to - from];
for (int i = 0; i < result.length; i++) {
result[i] = from + i;
}
return result;
}
static int[] evens(int[] values) {
return Arrays.stream(values).filter(v -> v % 2 == 0).toArray();
}
The following listing calls range(3, 7) and evens() with an array without an even number – the result of evens() is an array of length 0:
System.out.println(Arrays.toString(range(3, 7)));
System.out.println(Arrays.toString(evens(new int[] {1, 3, 5})));
[3, 4, 5, 6]
[]
final and Defensive Copies
final in front of an array variable only prevents you from assigning another array to the variable. You can still change the elements:
final int[] constants = {1, 2, 3};
constants[0] = 42;
System.out.println(Arrays.toString(constants));
[42, 2, 3]
There is no immutable array in Java. If you want to prevent code outside your class from changing an array that the class stores, you have to copy it both on the way in and on the way out – a so-called defensive copy. The following record does that in the constructor and in the accessor method:
record Measurements(int[] values) {
Measurements {
values = values.clone();
}
@Override
public int[] values() {
return values.clone();
}
}
After the constructor call, the following listing changes the array passed in and the array that values() returns – the record remains unaffected:
int[] raw = {7, 8, 9};
Measurements measurements = new Measurements(raw);
raw[0] = 0;
measurements.values()[1] = 0;
System.out.println(Arrays.toString(measurements.values()));
[7, 8, 9]
Each copy costs time and memory, though: if the record holds one million int values, each call of values() creates a new array of 4 MB.
If you don’t have to hand out the values as an array, you are better off storing an unmodifiable list in the record: List.copyOf() copies the values once in the constructor, and values() returns the list directly. Anyone who tries to change it gets an UnsupportedOperationException. With int values, however, the list takes more memory – about 20 MB instead of 4 MB for one million values, see Array or ArrayList?.
Varargs
A parameter of type int... – a so-called varargs parameter – is an int[]. The caller may pass any number of numbers, including none, and the compiler packs them into an array. The caller may, however, also pass an array itself:
static int sum(int... values) {
return Arrays.stream(values).sum();
}
The following listing calls sum() without an argument, with three numbers, and with an array:
System.out.println(sum());
System.out.println(sum(1, 2, 3));
System.out.println(sum(new int[] {4, 5}));
0
6
9
The parameter String[] args of the classic main() method is an array, too: it contains the command line arguments.
Multidimensional Arrays
In Java, a 2D array is an array of arrays: each element of an int[][] is an int[]. With two indexes, you access an element; with one, a whole row:
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
System.out.println(matrix[1][2]);
System.out.println(matrix.length + " rows, " + matrix[0].length + " columns");
System.out.println(Arrays.toString(matrix[0]));
6
2 rows, 3 columns
[1, 2, 3]
The article 2D Arrays in Java shows how to declare, initialize, iterate over, print, copy, and sort 2D arrays, what jagged arrays are, and when a flat array is faster.
Array or ArrayList?
An array and an ArrayList both store an ordered sequence of elements that you access via an index. The following table shows how they differ:
| Array | ArrayList | |
|---|---|---|
| Length | fixed | grows and shrinks |
| Element types | primitive types and objects | objects only |
| Methods | via the Arrays class | its own, e.g., add(), remove(), contains() |
Memory for one million int values | 4 MB | about 20 MB |
equals() and toString() | inherited from Object | compare and show the elements |
I recommend the ArrayList as the default. You use an array when the number of elements is fixed and you are dealing with primitive values – then it saves memory and the conversion into objects. The section Array vs. ArrayList of the ArrayList article explains how the memory requirement comes about and how the two differ otherwise.
How an Array Works Internally
An array is an object with a header, its length, and behind that all elements in one contiguous block of memory. Since Java 27, with compact object headers, an int[5] takes up 32 bytes:
The section How Much Memory Does a Java Array Take Up? of the article on array length shows how much other arrays take up, and the section Max Array Size in Java how large an array can get.
The contiguous block of memory makes arrays fast. The JVM calculates the address of an element directly from the index and the element size. And when a loop runs over the array, the CPU loads several elements with each cache line – with a cache line of 64 bytes, e.g., 16 int values. In addition, the CPU’s hardware prefetcher detects that the loop reads the array in order and loads the next cache lines before the loop needs them. The section Array vs. Linked List: Locality goes into more detail.
Every Array Type Is a Class
For each array type, there is a class of its own at runtime, and all arrays with the same element type are of this class. The name of the class starts with one square bracket per dimension, followed by the element type: e.g., I for int, and for a reference type an L with the class name and a semicolon. The superclass of an array class is Object, and it implements the interfaces Cloneable and Serializable – so arrays can be cloned and serialized:
int[] numbers = {1, 2, 3};
String[] names = {"Ada", "Linus"};
int[][] matrix = new int[2][2];
System.out.println(numbers.getClass().getName());
System.out.println(names.getClass().getName());
System.out.println(matrix.getClass().getName());
System.out.println(numbers.getClass().getSuperclass());
System.out.println(Arrays.toString(numbers.getClass().getInterfaces()));
[I
[Ljava.lang.String;
[[I
class java.lang.Object
[interface java.lang.Cloneable, interface java.io.Serializable]
This also explains the [I@4c873330 from the section Printing an Array: the inherited toString() method returns the class name, an @, and the hash code in hexadecimal notation. The following listing prints both side by side:
int[] numbers = {1, 2, 3};
System.out.println(numbers);
System.out.println(Integer.toHexString(numbers.hashCode()));
[I@1dbd16a6
1dbd16a6
Outlook: Flat Arrays with Project Valhalla
An object array contains references, and each object lives somewhere else on the heap. With Project Valhalla, Java 28 takes the first step towards changing that, as a preview: the JVM may embed the data of objects without identity, so-called value objects, directly into the elements of an array – without pointers and without a header of their own per element.
Covariance and the ArrayStoreException
A String is an Object – and that’s why in Java, a String[] is also an Object[]. This property is called covariance: the array types follow the inheritance of their element types. You can therefore assign a String[] to a variable of type Object[].
Via this variable, however, you could then write any object into the array, e.g., an Integer. The compiler cannot prevent this, because it only knows the type of the variable. The JVM therefore checks at runtime, on every write to an object array, whether the value matches the element type of the array, and otherwise throws an ArrayStoreException:
String[] names = {"Ada", "Linus"};
Object[] objects = names;
objects[1] = "Grace";
System.out.println(Arrays.toString(names));
try {
objects[1] = 42;
} catch (ArrayStoreException e) {
System.out.println(e);
}
[Ada, Grace]
java.lang.ArrayStoreException: java.lang.Integer
The string "Grace" fits into the String[], the number 42 doesn’t. The message of the exception names the class of the value that did not fit.
Generic lists, on the other hand, are not covariant: a List<String> is not a List<Object>. The following file ListCovariance.java attempts the same assignment as above, only with lists:
import java.util.ArrayList;
import java.util.List;
class ListCovariance {
void assign() {
List<String> strings = new ArrayList<>();
List<Object> objects = strings; // does not compile
}
}
ListCovariance.java:7: error: incompatible types: List<String> cannot be converted to List<Object>
List<Object> objects = strings; // does not compile
^
1 error
For a list, the compiler already catches the error that the JVM reports for an array only at runtime.
What the Check Costs
The benchmark StoreCheckBenchmark shows what the check costs when writing to an object array. It copies 1,000 strings element by element into a target array, in five variants. They differ in which type the variables for source and target have and which array the target really is. The table shows the time for all 1,000 elements:
| Type of the source | Type of the target variable | Target array | Time |
|---|---|---|---|
String[] | String[] | String[] | 360 ns |
String[] | Object[] | Object[] | 369 ns |
Object[] | Object[] | Object[] | 367 ns |
String[] | Object[] | String[] | 462 ns |
Object[] | Object[] | String[] | 583 ns |
The first three variants take the same time. In the first one, the check can never fail: String is final, so a String[] can only hold strings, and every value from the source is one. In the second and third, the target variable points to a real Object[], into which every object fits. The JIT compiler determines this once before the loop and then checks no element anymore.
The fourth variant copies into a String[] behind an Object[] variable and is 28% slower. Because the source is a String[], it is already clear before the loop that every value fits. Nevertheless, the machine code compares the element type of the target array with String once more for each element and checks the value for null. It has already loaded both classes before the loop, so the comparison needs no memory access.
The most expensive is the fifth variant: 62% slower than the first. Here, the source is only an Object[], too, and the JVM has to read the class of each object from the object’s header. To do so, it has to read the object itself from memory for each reference – the other variants don’t need that; they only copy the reference.
So the check only costs noticeable time where you write via a variable of a more general type into an array of a more specific type and the JVM does not already know the type of the value before the loop.
Why There Are No Generic Arrays
The check on writing requires that the array knows its element type at runtime. The JVM, however, does not know generic types at runtime: a List<String> becomes a List during compilation – this is called type erasure. At runtime, an array of type List<String>[] is an array of type List[] and can therefore only check whether an element is a List, but not whether it is a List<String>.
That’s why the compiler does not let you create an array whose element type is a type parameter or a parameterized type. You may, however, declare a variable of such a type. The following file GenericArrays.java declares one such variable each and tries to assign a new array to it:
import java.util.List;
class Box<T> {
T[] items = new T[10]; // does not compile
}
class Lists {
List<String>[] lists = new List<String>[3]; // does not compile
}
GenericArrays.java:4: error: generic array creation
T[] items = new T[10]; // does not compile
^
GenericArrays.java:8: error: generic array creation
List<String>[] lists = new List<String>[3]; // does not compile
^
2 errors
In both lines, the compiler only objects to the new – the declarations T[] items and List<String>[] lists, on the other hand, are allowed. You come across such a declaration mainly with varargs: a parameter T... is a T[], and the compiler creates the array for it at every place where the method is called – that is how Arrays.asList(T... a) works, for example.
The ArrayList gets by without a generic array: it stores its elements in an Object[] and casts them to the type parameter E when reading – a cast that the JVM does not check because it does not know E. The section How the ArrayList Works Internally goes into more detail.
Time Complexity
The following table shows the time complexity of the most important operations on an array with n elements:
| Operation | Time complexity |
|---|---|
| Reading or writing an element by index | O(1) |
| Searching for an element (linear search) | O(n) |
Searching for an element in a sorted array (binarySearch()) | O(log n) |
| Appending or removing an element (by copying) | O(n) |
Sorting (Arrays.sort()) | O(n log n) |
The article on Big O notation and time complexity explains what time complexity says and how to determine it. The article Array vs. Linked List compares array and linked list.
Common Mistakes
The following mistakes are the most common with arrays:
- Printing an array with
println(): The output shows the class name and hash code like[I@2b2fa4f7instead of the elements. UseArrays.toString(), and for nested arraysArrays.deepToString(). - Writing
length()instead oflength:array.length()does not compile, because the length is a field. Writearray.length–length()belongs toString,size()to lists. - Using the index
length: The last element has the indexlength - 1;array[array.length]throws anArrayIndexOutOfBoundsException. In a loop, the condition needs<, not<=. - Comparing arrays with
==orequals(): Both compare the references and returnfalsefor two arrays with the same contents. Compare withArrays.equals(), and nested arrays withArrays.deepEquals(). - Applying
Arrays.asList()to anint[]: The result is aList<int[]>with a single element – the array itself.contains(3)therefore returnsfalse, even if 3 is in the array, andCollections.reverse()changes nothing. UseArrays.stream(array).boxed().toList(). - Growing the list from
Arrays.asList():add()andremove()throw anUnsupportedOperationException. Copy it into anArrayListfirst withnew ArrayList<>(Arrays.asList(array)). - Calling
binarySearch()on an unsorted array: The result is undefined; often, an existing element is not found. Sort the array withArrays.sort()first, or search linearly. - Mistaking
clone()for a deep copy: A copy of an object array points to the same objects as the original. With mutable objects, copy the objects themselves, too. - Using an array as the key of a
HashMap: The map finds the entry only with the same array object, not with one with the same contents. Use aListor a record with individual fields as the key. - Appending one element after another with
Arrays.copyOf(): Each append copies the whole array; the running time grows quadratically. Collect the elements in anArrayList.
Summary
An array stores a fixed number of elements of the same type, numbered from 0. It is an object, and an array variable contains a reference to it – that’s why two variables can point to the same array.
Almost everything you want to do with an array is done by the static methods of the Arrays class: toString() for printing, sort() and binarySearch() for sorting and searching, equals() for comparing, fill() and copyOf() for filling and copying, asList() and stream() for converting.
An array cannot grow. Appending one element after another with Arrays.copyOf() costs quadratic running time: with 100,000 elements, it took 350 ms, with an ArrayList 0.25 ms. For comparing, use Arrays.equals() – it was faster than your own loop in every measurement, up to 11.5 times as fast for byte[]. In a String[], the easiest way to search is Arrays.asList().contains(), which was at most a quarter slower than your own loop.
Internally, every array is an object with a class of its own. Because arrays are covariant, the JVM checks the type of the value when writing to an object array. In the measurement, this check only cost time – up to 62% – when a String[] was behind an Object[] variable.
If you need a growing collection of objects, use the ArrayList. The article How to Initialize an Array in Java shows how to create arrays, the article Array Length in Java how to determine their length, and the article 2D Arrays in Java everything about arrays with several dimensions.
If you enjoyed this article, I’d appreciate a review on my ProvenExpert profile.




