The point is there is no 'generic function' to compare two arrays as 'equality' depends very much on your intentions; which you haven't yet made clear.
So if all you're interested in is whether they both add up to the same value then it's far simpler to sum each array independently and then compare the sum; though of course that's no guarantee that the two arrays contain the same int values. If you need to check whether the values in each array are identical at each index (i.e. the arrays are identical and in the same order) then the loop I posted would work. And if you wanted to check whether all values from the first array were present in the second array, regardless of order, you have two options. Either start by sorting them and then using the previous suggestion; or iterate over the second array for each value in the first. This is achieved easily enough with a nested loop, and then comparing the lengths of the two arrays to ensure equality; assuming all elements are matched:
- int matchedValues = 0;
- for(int i=0; i < arrayA.length; i++) {
- for(int j=0; j < arrayB.length; j++){
- // we can now compare each value in arrayA to each value in arrayB
- if(arrayA[i] == arrayB[j]) {
- println("value:" + arrayA[i] " is present in both arrays");
- matchedValues++;
- // no point continuing once we've confirmed there's a match...
- break;
- }
- }
- }
- // check if the arrays are 'equal'
- if(matchedValues == arrayA.length && arrayA.length == arrayB.length) {
- println("arrayB contains the same values as arrayA");
- }
Actually you'd do better to check the lengths matched first as if they don't that's obviously going to save you from wasting time iterating over them... Also which option you use (sorting + a single loop or nested loops) will again depend on your needs. You may not want to change the order of the values in the arrays, in which case the nested loop is the better option. Alternatively you could create copies of the two arrays to avoid affecting the order of the source arrays. I must admit I'm not sure which of these options is the best in terms of performance and you should also consider alternative storage options (e.g.
ArrayLists) which may be better suited for comparisons and may even have methods specifically for testing 'equality' (actually I'm guessing this is what you meant by a 'generic function' - so the answer may actually be to use an alternative storage mechanism).