# compare arrays

• 04-16-2010, 09:01 PM
innspiron
compare arrays
hi,

could some one tell me how to compare two array from particular element?

let say we have arrayA={24,1,21,44,56,99} and arrayB={3,0,21,44,56,99}

If I use Arrays.equals(arrayA,arrayB) it will check whole array, but I need let say to check if arrayA equals arrayB from second element and at this example it would give me true.

thanks
• 04-16-2010, 09:20 PM
al_Marshy_1981
Try Making a function to handle the problem.

pass the function the position in the array you want to check from and the two arrays to do the testing upon.

function prototype
Code:

```//set up the call boolean isTheSame; isTheSame=compareArrays(2,array1,arrray2); //the function header public boolean compareArrays(int indexToSearchFrom,int[]a,int[]b) { boolean status=false; //do comparison tests here return status }```
• 04-16-2010, 09:36 PM
innspiron
thanks for help, but what do you mean "do comparison tests here"? what kind of test? can you give me an example?

I created this method, but I think its just too much computation:

public static boolean compare(int[] a, int[] b) {
int[] tempA = new int[a.length - 2];
int[] tempB = new int[a.length - 2];
for (int i = 0; i < tempA.length; i++) {
tempA[i] = a[i + 2];
tempB[i] = b[i + 2];
}
if (Arrays.equals(tempA, tempB)) {
return true;
} else {
return false;
}
}

thanks
• 04-16-2010, 09:53 PM
al_Marshy_1981
when you pass the indexToSearch from value e.g. 2 you can use that as the start point (element of the array) to compare the arrays

Code:

```//set up the call boolean isTheSame; isTheSame=compareArrays(2,array1,arrray2); System.out.println(isTheSame); //the function header public boolean compareArrays(int indexToSearchFrom,int[]a,int[]b) { boolean status=false; //indexToSearchFrom is 2 for(int i=indexToSearchFrom;i<a.length;i++) {   //if the arrays dont match at any point break out of the loop and return    //false     if(a[i]!=b[i])     {         status=false;         break;       }else{             status=true;         } } return status```
in the above example if a[i] is not equal to b[i] then you know instantly the two arrays are not the same and you can break out of the loop and return false. Otherwise status is set to true, if the whole for loop runs then status will have to be true because a[i]!=b[i] condition will never have happened.
• 04-16-2010, 10:22 PM
innspiron
clear now. thanks a lot.