Jan 5, 2022

How to compare arrays in Java | Examples

In this post we will learn how to compare two arrays in java. So without wasting more time  lets get started. 

How to compare arrays in java, java program to compare two arrays in java


  What is comparing arrays really means: The comparing arrays means comparing or we can say checking first array elements are same like another one or not. for example: If we have two arrays like we can say arr1[] or arr2[] here, arr1 contains some values like 1,2,3,4,5 or arr2[] contains some values like 6,7,8,9,10. So we can see in this example arr1[] and arr2[] contains different values. 

Let's understand it with programming example's  :)

Java provides two inbuilt method's to compare arrays
1.  Arrays.equals()
2. Arrays.deepEquals()


1. Java Program to Compare two arrays using equals() method:


import java.util.Arrays;

public class ComparingArrays {

	public static void main(String[] args) {
		int arr1[] = {1,2,3,4,5};
		int arr2[] = {6,7,8,9,10};
		
		//comparing array contents
		if(Arrays.equals(arr1,arr2))
			System.out.println("Given two arrays are same");
		else
			System.out.println("Given arrays are not same");
			
	}
}

  Output of the above program is: 
Given arrays are not same



2. Java Program to Compare two arrays using deepEquals() method:

This method deeply compares two arrays. It is most useful when we want to compare multidimensional arrays.


import java.util.Arrays;

public class ComparingArrays {

	public static void main(String[] args) {
		int arr1[] = {1,2,3,4,5};
		int arr2[] = {1,2,3,4,5};
		
		//a1[] and a2[] contains only one elements
		Object a1[] = {arr1};
		Object a2[] = {arr2};
		
		//deeply comparing array contents
		if(Arrays.deepEquals(a1,a2))
			System.out.println("Given two arrays are same");
		else
			System.out.println("Given arrays are not same");
			
	}

}

  Output of the above program is:

Given two arrays are same


  Same above program using multidimensional array:



import java.util.Arrays;

public class ComparingArrays {

	public static void main(String[] args) {
		//defining multidimensional arrays
		int arr1[][] = {{1,2},{3,4}};
		int arr2[][] = {{1,2},{3,4}};
		
		//a1[] and a2[] contains only one elements
		Object a1[] = {arr1};
		Object a2[] = {arr2};
		
		//deeply comparing multidimensional array contents
		if(Arrays.deepEquals(a1,a2))
			System.out.println("Given two arrays are same");
		else
			System.out.println("Given arrays are not same");
			
	}
}


  Output of the above program is:

Given two arrays are same


Share your questions in the comment section given below....... :)


Share This:    Facebook Twitter

0 Comments:

Post a Comment

If you have any doubts, please discuss here...