Compare arrays equality equals()

Arrays.equals() method compares two arrays and tests whether they have the same elements are not. Returns a boolean value of true if they come with the same elements else false. Here, both arrays should have the same elements in the same order. If the order changes, the method returns false (even though they contain same elements).

Following is the method signature

  • static boolean equals(int array1[], int array2): Useful to compare the elements of two arrays. Returns true if both arrays array1 and array2 contain the same elements; here order is also important. This method is overloaded to accept arrays of type byte, boolean, double, long, short, char, float and Object.
Example on Compare arrays equality equals() uses the above method.
import java.util.Arrays;
public class ArraysEquals
{
  public static void main(String[] args) 
  {
    String stones1[] = { "diamond", "ruby", "emerald" };
    String stones2[] = { "diamond", "ruby", "emerald" };
    String stones3[] = { "diamond", "emerald", "ruby" };

    System.out.println("stones1 elements: " + Arrays.toString(stones1));
    System.out.println("stones2 elements: " + Arrays.toString(stones2));
    System.out.println("stones3 elements: " + Arrays.toString(stones3));

    System.out.println("\nstones1 and stones2 contain same elements: " + Arrays.equals(stones1, stones2));
    System.out.println("stones1 and stones3 contain same elements: " + Arrays.equals(stones1, stones3));

    if(Arrays.equals(stones1, stones2))
        System.out.println("stones1 and stones2 have same elements.");
  }
}


Compare arrays equality equals()
Output screen of Compare arrays equality equals()

String stones1[] = { “diamond”, “ruby”, “emerald” };
String stones2[] = { “diamond”, “ruby”, “emerald” };
String stones3[] = { “diamond”, “emerald”, “ruby” };

Three string array objects stones1, stones2 and stones3 are created with elements "diamond", "ruby" and "emerald". All the three arrays have the same elements but stones3 have a different order.

System.out.println(“stones1 elements: ” + Arrays.toString(stones1));

With toString() method of Arrays all the elements are printed. We know earlier toString() method avoids tedious for loops writing.

System.out.println(“\nstones1 and stones2 contain same elements: ” + Arrays.equals(stones1, stones2));

Arrays.equals(stones1, stones2) method compares the arrays stones1 and stones2. As they contain the same elements in the same order, the method returns true.

Arrays.equals(stones1, stones3) returns false as stones1 and stones3 contain same elements but in a different order.

if(Arrays.equals(stones1, stones2))

As equals() method returns a boolean value, it is best suitable to use with control structures as in the above code.

It looks similar to disjoint() method of Collections explained with ArrayList elements.

Leave a Comment

Your email address will not be published.