Sub topic 9
Comparing and Printing Array Contents
Two arrays can hold the same values without being the same array. Knowing the difference matters when you check results, test a program, or print values to understand what a program is doing.
This chapter uses java.util.Arrays, a Java class with methods for working with arrays. A method is a named action that code can call.
Same array or same contents?
An array variable holds a reference, which points to an array object. Two variables can point to the same array, or they can point to two separate arrays.
For arrays, the == operator checks whether two references point to the same array. It does not check the values inside the arrays.
Use Arrays.equals to compare the contents of one-dimensional arrays. It checks that the arrays have the same length and that values at each matching index are equal. An index is an element’s numbered position, starting at zero.
Save this program as CompareScores.java:
import java.util.Arrays;
public class CompareScores {
public static void main(String[] args) {
int[] first = {80, 90, 100};
int[] second = {80, 90, 100};
int[] shared = first;
System.out.println(first == second);
System.out.println(first == shared);
System.out.println(Arrays.equals(first, second));
second[1] = 85;
System.out.println(Arrays.equals(first, second));
}
}The import line lets the program use the short name Arrays. System.out.println prints a value on its own line.
Compile and run the program:
javac CompareScores.java
java CompareScoresThe output is:
false
true
true
falseHere is what each result means:
firstandsecondpoint to separate arrays, so==givesfalse.sharedandfirstpoint to the same array, so==givestrue.- The separate arrays initially have the same values in the same positions, so
Arrays.equalsgivestrue. - After
second[1]changes, the contents differ, soArrays.equalsgivesfalse.
The result of a comparison describes the arrays at the time of the call. If an element changes later, a new comparison can give a different result.
Length and order matter
Arrays.equals compares positions, not just the set of values present.
| First array | Second array | Equal contents? | Reason |
|---|---|---|---|
| `{1, 2}` | `{1, 2}` | Yes | Both positions match. |
| `{1, 2}` | `{2, 1}` | No | The values are in different positions. |
| `{1, 2}` | `{1, 2, 3}` | No | The lengths differ. |
| `{}` | `{}` | Yes | Both arrays are empty. |
For primitive arrays, compare arrays of the same element type. For example, Arrays.equals can compare two int[] arrays, but it cannot directly compare an int[] with a long[].
Comparing text and handling null
A String is a Java type for text. An array of String values holds references to text objects. When Arrays.equals compares these arrays, it compares the text values at matching positions.
A reference can also be null, which means it does not point to an object. Arrays.equals handles null array references and null elements.
Save this program as CompareNames.java:
import java.util.Arrays;
public class CompareNames {
public static void main(String[] args) {
String[] first = {"Ada", null, "Lin"};
String[] second = {"Ada", null, "Lin"};
String[] missing = null;
String[] alsoMissing = null;
System.out.println(Arrays.equals(first, second));
System.out.println(Arrays.equals(first, missing));
System.out.println(Arrays.equals(missing, alsoMissing));
second[0] = "ada";
System.out.println(Arrays.equals(first, second));
}
}Compile and run it with javac CompareNames.java and then java CompareNames. The output is:
true
false
true
falseThe first result is true because the matching text values and the two null elements are equal. A non-null array and a null reference are not equal. Two null array references are considered equal by Arrays.equals.
The final result is false because String comparison distinguishes uppercase and lowercase letters. "Ada" and "ada" are different text values.
For an array of other kinds of objects, Arrays.equals uses each element’s equals method to compare it with the matching element. The result therefore depends on how that kind of object defines equality. Not every kind compares its contents as String does.
Printing a one-dimensional array
Printing an array reference directly does not normally show its elements. For an int[], Java prints text that identifies the array’s type and object instead. That text can vary between runs.
Use Arrays.toString to get a readable representation of the elements. A string representation is text that describes a value.
Save this program as PrintScores.java:
import java.util.Arrays;
public class PrintScores {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
String[] names = {"Ada", "Lin"};
int[] missing = null;
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(missing));
}
}Compile and run it with javac PrintScores.java and then java PrintScores. The output is:
[80, 90, 100]
[Ada, Lin]
nullArrays.toString puts square brackets around a non-null array’s elements and separates them with commas. It returns the text "null" for a null array reference.
For an object array, it uses each element’s string representation. Text elements appear without quotation marks. As a result, the printed form is useful for people to read, but it is not always a clear way to save data for a program to read back.
Nested arrays need deep comparison
A multidimensional array is an array whose elements can themselves be arrays. For example, an int[][] can hold several int[] rows.
For nested arrays, Arrays.equals checks the outer array’s elements. Since those elements are themselves arrays, that check compares the row references rather than the values inside separate rows.
Use Arrays.deepEquals to compare nested contents. Use Arrays.deepToString to print nested contents.
Save this program as NestedContents.java:
import java.util.Arrays;
public class NestedContents {
public static void main(String[] args) {
int[][] first = {{1, 2}, {3}};
int[][] second = {{1, 2}, {3}};
System.out.println(Arrays.equals(first, second));
System.out.println(Arrays.deepEquals(first, second));
System.out.println(Arrays.deepToString(first));
second[1][0] = 4;
System.out.println(Arrays.deepEquals(first, second));
System.out.println(Arrays.deepToString(second));
}
}Compile and run it with javac NestedContents.java and then java NestedContents. The output is:
false
true
[[1, 2], [3]]
false
[[1, 2], [4]]The two outer arrays contain separate row arrays. That is why Arrays.equals returns false, even though the rows initially contain matching numbers. Arrays.deepEquals looks inside the rows, so it first returns true.
The rows do not need to have the same length as one another. They do need to match the corresponding rows in the other array. After the program changes the second row of second, the deep comparison returns false.
For a nested array, Arrays.toString describes the outer elements but does not list the numbers inside each row. Choose Arrays.deepToString when you want to see those numbers.
Arrays.deepEquals and Arrays.deepToString take an array of references at the outer level. An int[][] works because its outer elements are references to int[] rows. For a plain int[], use Arrays.equals and Arrays.toString.
Choosing the right check
| Goal | Use |
|---|---|
| Check whether two variables point to the same array | `first == second` |
| Compare one-dimensional array contents | `Arrays.equals(first, second)` |
| Compare nested array contents | `Arrays.deepEquals(first, second)` |
| Print one-dimensional array contents | `Arrays.toString(first)` |
| Print nested array contents | `Arrays.deepToString(first)` |
Choose based on the question you need to answer. Two references can point to different arrays while their contents are equal. Printing the contents can help you see those values, but a printed line is not a substitute for a content comparison in your program.
Exercise
Given int[] a = {4, 5}; and int[] b = {4, 5};, what do a == b and Arrays.equals(a, b) return?
Show answer
a == b returns false because the arrays are separate. Arrays.equals(a, b) returns true because their contents match.
Exercise
Two separately created int[][] arrays contain the same numbers in matching rows. Which method checks those numbers, and which method prints them?
Show answer
Use Arrays.deepEquals to compare the nested contents and Arrays.deepToString to print them.
Exercise
Does Arrays.equals consider {"Ada", "Lin"} equal to {"Lin", "Ada"}?
Show answer
No. The values are in different positions, and order matters.