Sunday, 5 April 2020

Java: equals() vs Arrays.equals

array1.equals(array2) method return true, if both the array references point to same object (same as array1 == array2), else false.

Arrays.equals() method is available in below forms, it return true if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.
public static boolean equals(byte[] a, byte[] a2)
public static boolean equals(short[] a, short[] a2)
public static boolean equals(int[] a, int[] a2)
public static boolean equals(long[] a, long[] a2)
public static boolean equals(float[] a, float[] a2)
public static boolean equals(double[] a, double[] a2)
public static boolean equals(char[] a, char[] a2)
public static boolean equals(boolean[] a, boolean[] a2)
public static boolean equals(Object[] a, Object[] a2)

App.java
package com.sample.app;

import java.util.Arrays;

public class App {

 public static void main(String args[]) {
  int[] data1 = { 2, 3, 5, 7 };
  int[] data2 = { 2, 3, 5, 7 };
  int[] data3 = data1;

  System.out.println("data1.equals(data2) : " + data1.equals(data2));
  System.out.println("data1.equals(data3) : " + data1.equals(data3));
  
  System.out.println("Arrays.equals(data1, data2) : " + Arrays.equals(data1, data2));
  System.out.println("Arrays.equals(data1, data3) : " + Arrays.equals(data1, data3));

 }

}

Output
data1.equals(data2) : false
data1.equals(data3) : true
Arrays.equals(data1, data2) : true
Arrays.equals(data1, data3) : true

Note
'Arrays.equals()'' do not work as expected for multidimensional arrays, it compares items of the 1st dimension for reference equality.

You may like

No comments:

Post a Comment