Check if two arrays are equal or not in Java
In this tutorial, we will learn how to check if two arrays are equal or not in Java. Firstly, using a simple program and secondly using a predefined library to do the same.
We will describe how two arrays can be equal when it fulfills two conditions.
1. No. of elements in the arrays is equal.
2. Values in the array should be the same even though they are not arranged properly.
for example:
Two arrays are equal or not in java
Basic Approach in this program:
1. Firstly, check no of an element in the first array should be equal to the two-second one.
2. If the number of elements is equal but their arrangement is not in the proper way then using sort we sort both arrays.
Program without predefined library
package array; import java.util.Arrays; import java.io.*; public class Array { public static boolean isequal(int a[],int b[],int len1,int len2) { //to sort both the arrays Arrays.sort(a); Arrays.sort(b); for(int i=0;i<len1;i++) { if(a[i]!=b[i]) return false; return true; } return true; } public static void main(String[] args) { int a[]={1,4,6,8,36}; int b[]={1,4,36,6}; //to find length of both arrays int len1=a.length; int len2=b.length; if(len1!=len2) {System.out.println("not equal"); return; } if(isequal(a,b,len1,len2)) {System.out.println(" equal");} else {System.out.println(" not equal");} }}
output: not equal
Program with a predefined library
package comparearray; import java .util.Arrays; import java.io.*; public class Comparearray { public static void main(String[] args) { int a[]={11,63,8,43}; int b[]={63,43,11,8}; int n = a.length; int m = b.length; if(m!=n) {System.out.println(" not equal"); return; } Arrays.sort(a); Arrays.sort(b); boolean ans=Arrays.equals(a,b); if(ans==true) {System.out.println("equal"); }else {System.out.println(" not equal"); }}}
output: equal
Thus from the above two ways, we can check whether two arrays are equal or not.
Leave a Reply