Compare two arrays of primitives in Java?
Solution 1
Change your first comparison to be:
if (a == b)
return true;
This not only catches the "both null" cases, but also "compare an array to itself" case.
However, for a simpler alternative - use Arrays.equals
which has overloads for each primitive type. (The implementation is very similar to yours, except it hoists the array length out of the loop. On .NET that can be an anti-optimization, but I guess the JRE library implementors probably know better for the JVM :)
Solution 2
I think the most efficient should be to use the helper methods in the Arrays class, because they might be implemented more cleverly. So in this case, use
Arrays.equals(a, b);
Comments
-
Josh almost 2 years
I know about Arrays.deepEquals(Object[], Object[]) but this doesn't work for primitive types (due limitations of arrays and autoboxing, see this related post).
With that in mind, is this the most efficient approach?
boolean byteArrayEquals(byte[] a, byte[] b) { if (a == null && b == null) return true; if (a == null || b == null) return false; if (a.length != b.length) return false; for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; }
-
Brett about 15 yearsYou may find the VM ignore the implementation in the library and inline its own.