I am trying to write code to compare two arrays. In the first array I have put my own digits, but the second the array takes numbers from the input file. The size of this array is determined by the first number in the file while the first array is always of size 10. The length must be the same for both arrays as well as the numbers.
My code is below:
public static void compareArrays(int[] array1, int[] array2) { boolean b = false; for (int i = 0; i < array2.length; i++) { for (int a = 0; a < array1.length; a++) { if (array2[i] == array1[a]) { b = true; System.out.println("true"); } else { b = false; System.out.println("False"); break; } } } }
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
Java Arrays class provides the equals() method to compare two arrays. It iterates over each value of an array and compares the elements using the equals() method.
Syntax : public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero. Example :To show working of java.
From what I see you just try to see if they are equal, if this is true
, just go with something like this:
boolean areEqual = Arrays.equals(arr1, arr2);
This is the standard way of doing it.
Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:
Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.
Sorry for missing that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With