Description

On this document we will be showing a java example on how to use the equals() method of Arrays Class. This method is overloaded in such a way that all possible data type is handled. Basically the equals() method returns true if the two specified arrays equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two array references are considered equal if both are null.

Notes:

  • The equals() had one deficiency, it will not be able to test properly the equality of multi dimensional array. I would recommend using deepEquals() in handling multi dimensional array.

Method Syntax

public static int equals(datatype[] a, dataype b)

Method Returns

The equals() method returns true if the two arrays are equal.

Compatibility

Requires Java 1.2 and up

Java Arrays equals() Example

Below is a java code demonstrates the use of equals() method of Arrays class. The example presented might be simple however it shows the behavior of the equals() method.

package com.javatutorialhq.java.examples;

import java.util.Arrays;

/*
 * A java example source code to demonstrate
 * the use of equals() method of Arrays class
 */

public class ArraysEqualsExample {

	public static void main(String[] args) {

		// initialize a new String array
		String[] names = new String[]{
			"Alfred","Beth","Stan"	
		};
		
		Object[] data = new Object[3];
		data[0] = "Alfred";
		data[1] = "Beth";
		data[2] = "Stan";
		
		// test for equality		
		boolean result = Arrays.equals(names, data);
		if(result){
			System.out.println("They are equals");
		}
		else{
			System.out.println("They are not equals");
		}
				
	}
}

The above java example source code demonstrates the use of equals() method of Arrays class. We simply 2 array and we test the equality using the equals method. The result is printed out if they are equal.

Sample Output

Below is the sample output when you run the above example.

Arrays equals() example output