Two arrays are equal if they contain the same elements in the same order. In java, we can compare two Boolean Arrays in 2 ways:
- By using Java built-in method that is .equals() method.
- By using the Naive approach.
Examples:
Input : A = [true , true , false] A1 = [true, true, false] Output: Both the arrays are equal. Input : A = [true, true, false] A1 = [true, false, true] Output: Both the arrays are not equal.
Method 1:
Array class in Java provides the method Arrays.equals() to check whether two arrays are equal or not.
Syntax:
public static boolean equals(boolean[] a, boolean[] a1)
Parameters:
a - one array to be tested for equality a1 - another array to be tested for equality
Returns: It returns true if both the arrays are equal else returns false.
Code:
Java
// Java Program to Compare two Boolean // Arrays using built-in function import java.util.Arrays;
class GFG {
public static void main(String[] args)
{
// initializing both the boolean arrays
boolean [] a = new boolean [] { true , true , false };
boolean [] a1 = new boolean [] { true , true , false };
// Displaying Array1
System.out.println( "Array1..." );
for ( int i = 0 ; i < a.length; i++)
{
System.out.println(a[i]);
}
// Displaying Array2
System.out.println( "Array2..." );
for ( int j = 0 ; j < a1.length; j++)
{
System.out.println(a1[j]);
}
// comparing array1 and array2
boolean result = Arrays.equals(a, a1);
if (result)
{
System.out.println( "Both the arrays equal " );
}
else
{
System.out.println(
"Both the arrays not equal " );
}
}
} |
Output
Array1... true true false Array2... true true false Both the arrays equal
Method 2:
- In this, we will use the Naive approach to compare two arrays.
- We can run a for loop and check every element of the array and compare each one of them.
Java
// Java Program to Compare two Boolean // Arrays using Naive approach import java.io.*;
class GFG {
public static void main(String[] args)
{
// initializing both the boolean arrays
boolean [] a = new boolean [] { true , true , false };
boolean [] a1 = new boolean [] { true , true , false };
// Displaying Array1
System.out.println( "Array1..." );
for ( int i = 0 ; i < a.length; i++)
{
System.out.println(a[i]);
}
// Displaying Array2
System.out.println( "Array2..." );
for ( int j = 0 ; j < a1.length; j++)
{
System.out.println(a1[j]);
}
// Comparing both the arrays
for ( int i = 0 ; i < a.length; i++)
{
// if any element is found different we will
// print our ans and exit the program.
if (a[i] != a1[i])
{
System.out.println(
"Both the arrays equal " );
System.exit( 0 );
}
}
System.out.println( "Both the arrays equal " );
}
} |
Output
Array1... true true false Array2... true true false Both the arrays equal