Checking whether two arrays are equal means checking that they have the same length and the same elements in the same order. Java has a one-line answer, but interviewers usually also want the manual comparison, and a follow-up on comparing arrays where order doesn't matter.
Solution 1: Arrays.equals
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(Arrays.equals(a, b)); // true
System.out.println(a == b); // false: compares references, not contents
For arrays of arrays, use Arrays.deepEquals(x, y).
Solution 2: Manual Comparison
public class CompareArrays {
public static boolean areEqual(int[] a, int[] b) {
if (a == b) return true;
if (a == null || b == null || a.length != b.length) return false;
for (int i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(areEqual(new int[]{1, 2, 3}, new int[]{1, 2, 3})); // true
System.out.println(areEqual(new int[]{1, 2, 3}, new int[]{3, 2, 1})); // false
}
}
Follow-Up: Same Elements in Any Order
// Sort copies, then compare (O(n log n))
int[] x = {3, 1, 2}, y = {1, 2, 3};
int[] xs = x.clone(), ys = y.clone();
Arrays.sort(xs); Arrays.sort(ys);
System.out.println(Arrays.equals(xs, ys)); // true
// Or count occurrences with a map (O(n)), which also handles duplicates correctly
Map<Integer, Integer> count = new HashMap<>();
for (int v : x) count.merge(v, 1, Integer::sum);
for (int v : y) count.merge(v, -1, Integer::sum);
boolean sameElements = x.length == y.length && count.values().stream().allMatch(c -> c == 0);
Interview Notes
==compares references;a.equals(b)on arrays is also a reference comparison, because arrays don't overrideequals.- Manual comparison is O(n) time and O(1) space; check lengths first to exit early.
- For String or object arrays, compare elements with
Objects.equalsto handle nulls.
FAQs
Why does array1.equals(array2) return false for identical arrays?
Arrays inherit equals from Object, which compares references. Use Arrays.equals (or Arrays.deepEquals for nested arrays) to compare contents.