How to Compare Two Arrays in Java without built-in functions
In this blog, we will see how to compare two arrays in java without in-built functions. This will be asked in the most of the interview questions.
In the below snippet, we have done the following:
- Created two arrays of same datatype and assigned those with some elements
- Created a helper class with parameters of these two arrays
- Inside the helper class, to compare the arrays we have done the following
- Firstly, we compared both the declared arrays length are equal or not using arrayname.length() and returned the value
- Then, we have iterated a for loop based on array.length() and then compared the arrays index is equal or not and returned the value.
- In the main method, we mentioned an If condition which will validate the result based on the returned value.
package Javaprograms; public class CompareArraysWithoutInBuiltFunctions { public static void main(String[] args) { String a[] = {"apple","bat","cat"}; String b[] = {"apple","bat","catt"}; if(arraysCompareCheck(a, b)){ System.out.println("Both arrays are equal"); } else { System.out.println("Both arrays are not equal"); } } public static boolean arraysCompareCheck(String a[], String b[]){ if(a.length!=b.length){ return false; } else { for(int i=0;i<a.length;i++) { if(a[i]!=b[i]) { return false; } } } return true; } }
Output: -------- Both arrays are not equal
Here, It’s better to use the Object class as a parameter as it is the super class which can inherit all the datatypes and supports whatever the array’s datatype is.
Below is the snippet which uses the Object class as a parameter:
If you’re using an integer array with an object class parameter, Make sure to use the derived datatype Integer instead of Int
package Javaprograms; public class CompareArraysWithoutInBuiltFunctions { public static void main(String[] args) { //String a[] = {"apple","bat","cat"}; //String b[] = {"apple","bat","catt"}; Integer a[] = {1,2,19}; Integer b[] = {1,2,19}; if(arraysCompareCheck(a, b)){ System.out.println("Both arrays are equal"); } else { System.out.println("Both arrays are not equal"); } } public static boolean arraysCompareCheck(Object a[], Object b[]){ if(a.length!=b.length){ return false; } else { for(int i=0;i<a.length;i++) { if(a[i]!=b[i]) { return false; } } } return true; } }
Output: ------- Both Arrays are equal
Please watch the Youtube video for better understanding.