check if two arrays are equal in java
Code snippet on how to check if two arrays are equal in java
boolean equals(int[] a, int[] b) {
if (a.length != b.length) {
return false;
}
for (int i=0; i < a.length; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
This code is used to check if two arrays, a and b, are equal. First, the code checks if the arrays have the same length, since equal arrays should have the same amount of elements. If they don’t, the code returns “false” immediately. If they do, the code continues to the main loop of the code. In the main loop, the code compares each element of the two arrays, one by one. If at any point the two elements being compared are not equal, the code returns “false”. If it reaches the end of the loop without finding any differences, the code can conclude that the arrays are equal and returns “true”.