Java, Software Development

Java Compare Multidimensional Arrays Of Reference Types

This post shows how to compare two multidimensional arrays of reference types in Java. The codes will examine if they are the same in terms of element values and their locations. For example, we want to compare a modified array with the original copy of that array.

Java Compare Basics

To make Java compare objects in a non-default way, we need to override some class methods. These methods are hashCode and equals. Overriding them gives us the chance to decide how we compare objects using their properties – instance variables. We may not want to include all object properties in a comparison. For instance, we only need to compare two Persons’ last names and not their first names or ages.

Beyond object-to-object comparison, we can compare multidimensional arrays of objects. The same principle applies, but we are comparing a group of objects with another group.

Using Arrays.deepEquals With Multidimensional Arrays of Strings

Here we have two multidimensional arrays, and we have to know if they are the same or not.

The codes output false because the two arrays are different. The strCopyValues has a value of “1” at strCopyValues[0][0] and an additional element “k.”

Using Arrays.deepEquals With Multidimensional Arrays of

Other Reference Types

Here is an example that uses the Person objects instead of String objects for multidimensional arrays in Java. We will compare the multidimensional arrays similarly, but we need to override the hashCode and equals methods to facilitate the Java comparison.

Person Class

We have the following codes, and we overrode the hashCode and equals methods.

Pet Class

To make the codes more interesting, each Person object can have a Pet object. We also overrode its hashCode and equals methods.

Main class

Now let us look at our main class that uses the Person and Pet classes.

Output

This is (now) part of a reboot Java tutorial.

You Might Also Like