Java-Programming-Docs Help

Checking for Array Equality

Checking for equality between two arrays can be done in one of two manners depending upon the type of equality you are looking for. Are the array variables pointing to the same place in memory and thus pointing to the same array? Or are the elements of two arrays comparatively equivalent.

Checking for two reference to the same memory space is done with the double equal sign operator ==. For example the prior components and buttons variables would be equal in this case since one is a reference to the other:

package cloud.yebei.java.collections.arrays; public class ArrayEquality { public static void main(String[] args) { java.awt.Button[] buttons = { new java.awt.Button("One"), new java.awt.Button("Two"), new java.awt.Button("Three") }; java.awt.Component[] components = buttons; System.out.println(components == buttons); // => true } }

However, if you compare an array to a cloned version of that then these would not be equal as far as == goes. Since these arrays have the same elements but exists in different memory space, they are different. In order to have a clone of an array to be "equal" to the original, you can use the equals() method of the java.util.Arrays class.

package cloud.yebei.java.collections.arrays; public class CloneArrayEquality { public static void main(String[] args) { String[] alphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H"}; String[] clone = alphabets.clone(); boolean isEqual = java.util.Arrays.equals(clone, alphabets); System.out.println("isEqual: " + isEqual); // => isEqual: true } }

This will check for equality with each element. In the case where the arguments are arrays of objects, the equals() method of each object will be used to check for equality. Arrays.equals() works for arrays that are not clones, too.

    Last modified: 16 July 2024