Compare two arrays of primitives in Java?

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 🙂

Leave a Comment