1. Member
Join Date
Mar 2010
Posts
12
Rep Power
0

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

2. Senior Member
Join Date
Feb 2010
Location
Waterford, Ireland
Posts
748
Rep Power
11
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
Java Code:
```//set up the call
boolean isTheSame;
isTheSame=compareArrays(2,array1,arrray2);

public boolean compareArrays(int indexToSearchFrom,int[]a,int[]b)
{
boolean status=false;

//do comparison tests here

return status
}```

3. Member
Join Date
Mar 2010
Posts
12
Rep Power
0
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

4. Senior Member
Join Date
Feb 2010
Location
Waterford, Ireland
Posts
748
Rep Power
11
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

Java Code:
```//set up the call
boolean isTheSame;
isTheSame=compareArrays(2,array1,arrray2);
System.out.println(isTheSame);

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.

5. Member
Join Date
Mar 2010
Posts
12
Rep Power
0
clear now. thanks a lot.

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•