Java equals with arrays

Checking if Two Arrays are Equal in Java

Learn to compare two arrays using different techniques in Java. We will learn the array comparison from using simple for loops to inbuilt Java APIs.

1. How is the Arrays Comparison Done?

In Java or any other programming language, the basics behind comparing two arrays are the same. Two arrays are equal if:

  • both are either null or non-null.
  • both are of the same type.
  • both have an equal number of items.
  • both have the same item in the corresponding indices in the same order.
  • both arrays are multi-dimensional, then inner arrays also need to be equal.

Now that we know what makes two arrays equal, it is easy to write a function that will check it.

2. Checking Array Equality with java.util.Arrays

For any problem, if you have a Java API available within JDK, always prefer to use it rather than writing it yourself. You should write a new function only when you have a very strong reason to do it, else use the inbuilt APIs.

Arrays class provides many useful methods for operating on arrays. For checking array equality, it provides two methods that have multiple overloaded forms to accept different array types:

  • public static boolean equals(array1, array2) : returns true if array1 and array2 are equal to one another i.e. they contain the same elements in the same order.
  • public static boolean equals(array1, array2, comparator) : returns true if array1 and array2 are equal to one another. Two array items e1 and e2 are considered equal if comparator.compare(e1, e2) == 0 .
  • public static boolean deepEquals(array1, array2) : returns true if array1 and array2 are deeply equal to one another. This method is appropriate for use with nested arrays of arbitrary depth.
Читайте также:  Convert to javascript timestamp

The simple arrays are 1-D arrays that are not nested. In simple arrays, we can have any type of item, and it is necessary to understand how to deal with them.

  • Primitive and String Arrays: Primitives and strings are always compared by their value so we can safely use the equals() API.
  • Object Types: In this case, we need to know how the two array items will be checked for equality. If the default object equality has to be used, or class has overridden the Object.equals() method then we can use the Arrays.equals(), else we must use the Comparator version of API to provide the custom object equality logic.
String[] a1 = ; String[] a2 = ; String[] a3 = ; boolean matches = Arrays.equals(a1, a2); //true matches = Arrays.equals(a1, a3); //false

To check the nested array’s equality, we must use the deepEquals() API.

It is important to note that deepEquals() only works with object types, so deepEquals() cannot be used with primitive arrays, but we can use it for any simple or nested arrays.

String[][] a4 = < , >; String[][] a5 = < , >; boolean matches = Arrays.deepEquals(a4, a5); //true

3. Array Comparison with ‘For-loop’

For some reason, if we cannot use the Arrays class, we can write our own method and add the custom logic there.

For example, we do not declare arrays equal if both arrays are null. In this case, we can write our own function where we iterate over the array of items in a for loop and compare the items one by one. There may be more compelling reasons for others.

In the following method checkArrayEqualityWithForLoop() , we are writing the code for checking the equality of two simple arrays. Feel free to modify the logic as you want.

public static boolean checkArrayEqualityWithForLoop(String[] a1, String[] a2) < if (a1 == a2) < return true; >if (a1 == null || a2 == null) < return false; >int n = a1.length; if (n != a2.length) < return false; >for (int i = 0; i < n; i++) < if (!a1[i].equals(a2[i])) < return false; >> return true; >

4. Array Comparison with Stream API

To make code more readable, we can use the stream API‘s IntStream.range() in place of the for-loop. Else the remaining logic is the same as the previous example.

public static boolean checkEqualityWithStream(String[] a1, String[] a2) < if (a1 == a2) < return true; >if (a1 == null || a2 == null || a1.length != a2.length) < return false; >return IntStream.range(0, a1.length).allMatch(i -> a1[i].equals(a2[i])); >

In this tutorial, we learned to check if two arrays are equal in Java. We learned the rules to check the equality of simple arrays and nested arrays. Also, we learned to take care of equality of array items using Object.equals() and Comparator.

Finally, we learned to use the Java APIs and well the simple for-loop for customizing the array equality logic.

Источник

Java Array equals Method

Java Array Equals Method 1

The Java Arrays.equals Method is one of the Java Array Methods to check whether user-specified arrays are equal or not. If they are equal, it returns Boolean TRUE; otherwise, FALSE.

This article will show how to compare the Arrays using Java equals method with an example. The syntax of the Arrays.equals is as shown below.

Java Array equals Method syntax

There are nine different Java equals methods to compare the user-specified Arrays. The following method will accept two Boolean Arrays (a1 and a2) as the parameters and check whether a1 and a2 are equal or Not. If they are equal, it returns a boolean TRUE; otherwise, FALSE.

public static boolean equals(Boolean[] al, Boolean[] a2); // It will return Boolean //In order to use in program Arrays.equals(Boolean[] al, Boolean[] a2);

This Java method accepts two Byte Arrays (b1 and b2) and checks whether b1 and b2 are equal. If they are equal, it returns a boolean TRUE otherwise, FALSE.

public static boolean equals(Byte[] bl, Byte[] b2); // It will return Boolean //In order to use in program Arrays.equals(Byte[] bl, Byte[] b2);

This Java function accepts two Short Arrays(s1 and s2) as the parameters and checks whether s1 and s2 are equal or Not. If they are equal, it returns a boolean TRUE otherwise, FALSE.

public static boolean equals(short[] sl, short[] s2); // It will return Boolean //In order to use in program Arrays.equals(short[] sl, short[] s2);

The below method accepts two Character Arrays(c1 and c2) as the parameters and checks whether c1 and c2 are equal or Not. If they are equal, it returns a boolean TRUE otherwise, FALSE.

public static boolean equals(char[] cl, char[] c2); // It will return Boolean //In order to use in program Arrays.equals(char[] cl, char[] c2);

This Java method will accept two Integer Arrays (i1 and i2) as the parameters and check whether i1 and i2 is equal or Not. If they are equal, it returns a boolean TRUE; otherwise, FALSE.

public static boolean equals(int[] il, int[] i2); // It will return Boolean //In order to use in program Arrays.equals(int[] il, int[] i2);
public static boolean equals(long[] ll, long[] l2); // It will return Boolean //In order to use in program Arrays.equals(long[] ll, long[] l2);

This Java method will accept two Double Arrays (d1 and d2) as the parameters and check whether d1, d2 are equal or Not. If they are equal, it returns a boolean TRUE otherwise, FALSE.

public static boolean equals(double[] dl, double[] d2); // It will return Boolean //In order to use in program Arrays.equals(double[] dl, double[] d2);

The following Java method will accept two Float Arrays(f1 and f2) as the parameters and check whether f1, f2 are equal or Not. If they are equal, it returns a boolean TRUE otherwise, FALSE.

public static boolean equals(float[] fl, float[] f2); // It will return Boolean //In order to use in program Arrays.equals(float[] fl, float[] f2);

It accepts two Object Arrays (Obj1 and Obj2) as the parameters and checks whether Obj1 and Obj2 is equal or Not. If they are equal, it returns a boolean TRUE otherwise, FALSE.

public static boolean equals(Object[] Objl, Object[] Obj2); // It will return Boolean //In order to use in program Arrays.equals(Object[] Objl, Object[] Obj2);

Java equals to compare Byte Arrays

In this Java program, we declared three byte Arrays with random elements. Next, we will call the public static boolean equals (byte[] b1, byte[] b2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class ByteEquals < public static void main(String[] args) < byte[] byteArray = ; byte[] bytArray = ; byte[] bitArray = ; //Checking for Equality System.out.println(Arrays.equals(byteArray, bitArray)); if(Arrays.equals(byteArray, bytArray)) < System.out.println("Two Byte Arrays are Equal"); >else < System.out.println("Byte Arrays are Not Equal"); >> >

Java Array Equals Method 1

First, we declared three byte Arrays and assigned some random values as the elements.

Next, we used the method to check whether the above-specified byte arrays (byteArray, bitArray) are equal or not.

  • If the statement inside the If is True (If they are equal), then the System.out.println(” Two Byte are Equal “); statement printed.
  • Else System.out.println(“Byte are Not Equal”); statement will print.

Java equals to compare Boolean Arrays

In this program, we declared three boolean arrays with random elements. Then we will call the public static boolean equals (boolean[] a1, boolean[] a2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class BooleanEquals < public static void main(String[] args) < boolean[] bool = ; boolean[] boolArray = ; boolean[] anBoolArray = ; //Checking for Equality System.out.println(Arrays.equals(bool, boolArray)); if(Arrays.equals(bool, anBoolArray)) < System.out.println("Both are Equal"); >else < System.out.println("Not Equal"); >> >

Java equals to compare Short Arrays

In this program, we declared three short arrays with random elements. Then we will call the public static boolean equals (short[] s1, short[] s2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class ShortEquals < public static void main(String[] args) < short[] ShtArray = ; short[] ShrtArray = ; short[] ShortArray = ; //Checking for Equality System.out.println(Arrays.equals(ShtArray, ShrtArray)); if(Arrays.equals(ShrtArray, ShortArray)) < System.out.println("Both are Equal"); >else < System.out.println("Not Equal"); >> >

Java equals to compare Integer Arrays

In this Java program, we declare three integer arrays. Then we will call the public static boolean equals (int[] i1, int[] i2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class IntEquals < public static void main(String[] args) < int[] intArray = ; int[] itArray = ; int[] anIntArray = ; //Checking for Equality System.out.println(Arrays.equals(intArray, anIntArray)); if(Arrays.equals(intArray, itArray)) < System.out.println("Both are Equal"); >else < System.out.println("Not Equal"); >> >

compare Long Arrays

In this Java program, we declared three long arrays with random elements. Then we will call the public static boolean equals (long[] l1, long[] l2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class LongEquals < public static void main(String[] args) < long[] LnArray = ; long[] LngArray = ; long[] LongArray = ; //Checking for Equality System.out.println(Arrays.equals(LnArray, LongArray)); if(Arrays.equals(LnArray, LngArray)) < System.out.println("Both the Long are Equal"); >else < System.out.println("Long are Not Equal"); >> >
false Both the Long are Equal

compare Double Arrays

In this Java program, we declared three double arrays with random elements. Then we will call the public static boolean equals (double[] d1, double[] d2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class DoubleEquals < public static void main(String[] args) < double[] dblArray = ; double[] doubleArray = ; double[] andoubleArray = ; //Checking for Equality System.out.println(Arrays.equals(dblArray, andoubleArray)); if(Arrays.equals(dblArray, doubleArray)) < System.out.println("Both the Double are Equal"); >else < System.out.println("Double are Not Equal"); >> >
false Both the Double are Equal

Java equals to compare Float Arrays

In this Java program, we declared three float arrays with random elements. Then we will call the public static boolean equals (float[] f1, float[] f2) method to check whether they are equal or not.

package ArrayMethods; import java.util.Arrays; public class FloatEquals < public static void main(String[] args) < float[] floatArray = ; float[] fltArray = ; float[] anfloatArray = ; //Checking for Equality System.out.println(Arrays.equals(floatArray, fltArray)); if(Arrays.equals(floatArray, anfloatArray)) < System.out.println("Both the Float Arrays are Equal"); >else < System.out.println("Float Arrays are Not Equal"); >> >
true Float Arrays are Not Equal

compare Char Arrays

In this program, it calls the public static boolean equals (char[] c1, char[] c2) to check whether they are equal.

package ArrayMethods; import java.util.Arrays; public class CharEquals < public static void main(String[] args) < char[] CharArray = ; char[] CharacterArray = ; char[] Character = ; //Checking for Equality System.out.println(Arrays.equals(CharArray, CharacterArray)); if(Arrays.equals(CharacterArray, Character)) < System.out.println("Both are Equal"); >else < System.out.println("Not Equal"); >> >

Compare Objects Arrays

In this Java program, Javac calls the public static boolean equals (Object[] Obj1, Object[] Obj2) to check whether they are equal.

package ArrayMethods; import java.util.Arrays; public class ObjectEquals < public static void main(String[] args) < String[] strArray = ; String[] stringArray = ; String[] strngArray = ; //Checking for Equality System.out.println(Arrays.equals(strArray, stringArray)); if(Arrays.equals(stringArray, strngArray)) < System.out.println("Both are Equal"); >else < System.out.println("Not Equal"); >> >
  • Java Tutorial
  • Java Operators
    • Arithmetic Operators
    • Assignment Operators
    • Bitwise Operators
    • Increment and Decrement
    • Logical Operators
    • Relational Operators
    • Ternary Operator
    • If Statement
    • If Else Statement
    • Nested If Statement
    • Else If Statement
    • Break Statement
    • Continue Statement
    • Switch Case
    • Method Overloading
    • Introduction to Math Library
    • abs Method
    • copySign Function
    • cbrt Function
    • ceil Function
    • floor Function
    • getExponent Function
    • IEEEremainder Function
    • max Function
    • min Function
    • pow Function
    • random Function
    • rint Function
    • round Function
    • nextUp Function
    • nextAfter Function
    • scalb Function
    • signum Function
    • sqrt Function
    • ulp Function
    • exp Function
    • expm1 Function
    • log Function
    • log1p Function
    • log10 Function
    • toRadians Function
    • toDegrees Function
    • sin Function
    • asin Function
    • sinh Function
    • cos Function
    • acos Function
    • cosh Function
    • tan Function
    • atan Function
    • atan2 Function
    • tanh Function
    • hypot Function
    • String methods Introduction
    • charAt Method
    • codePointAt Method
    • codePointBefore Method
    • codePointCount Method
    • compareToIgnoreCase
    • compareTo Method
    • concat Method
    • contains Method
    • contentEquals Method
    • copyValueOf Method
    • endsWith Method
    • equals Method
    • equalsIgnoreCase
    • format Method
    • getBytes Method
    • hashCode Method
    • indexOf Method
    • intern Method
    • isEmpty Method
    • length Method
    • lastIndexOf Method
    • matches Method
    • offsetByCodePoints Method
    • regionMatches Method
    • replaceAll Method
    • replaceFirst Method
    • split Function
    • startsWith Method
    • substring Method
    • subSequence Method
    • toCharArray Method
    • toLowerCase Method
    • toString Method
    • toUpperCase Method
    • trim Method
    • valueOf Method
    • Array Methods Introduction
    • Arrays copyOfRange
    • Arrays.copyOf Method
    • Array equals Method
    • Array Fill
    • Array Sort
    • Array toString

    Источник

Оцените статью