How to check whether all elements in two arrays are the same?
How to make it return true if all values are the same?
I have tried different ways but couldn't succeed.
How to check whether all elements in two arrays are the same?
How to make it return true if all values are the same?
I have tried different ways but couldn't succeed.
Probably try something like this:
public static boolean checkIdentical(int[][] targetArray) {
for (int i = 1; i < targetArray.length; i++) {
for (int j = 0; j < targetArray[i].length; j++) {
if (targetArray[i][j] != targetArray[0][j]) {
return false;
}
}
}
return true;
}
Caveat:
If the arrays can have variable lengths like this:
int[][] identicalArray = {{3, 3, 3, 4}, {3, 3, 3}};
Then the condition will be:
if (targetArray[i].length != targetArray[0].length
|| targetArray[i][j] != targetArray[0][j]) {
return false;
}
You can do in a single loop with Arrays.equals() method.
public static boolean checkIdentical(int[][] targetArray) {
int[] prev = null;
for (int[] a : targetArray) {
if (prev != null && !Arrays.equals(a, prev))
return false;
prev = a;
}
return true;
}
need to import java.util.Arrays.
A possible solution here:
public static void main(String[] args) {
int[][] identicalArray = { { 3, 3, 3 }, { 3, 3, 3 } };
int[][] nonIdenticalArray = { { 1, 2, 3 }, { 3, 2, 1 } };
System.out.println("identicalArray all identical? " + checkIdentical(identicalArray));
System.out.println("nonIdenticalArray all identical? " + checkIdentical(nonIdenticalArray));
}
public static boolean checkIdentical(int[][] targetArray) {
int[] array1 = targetArray[0];
for(int[] array : targetArray) {
if (!Arrays.equals(array1, array))
return false;
}
return true;
}
What happens in checkIdentical :
targetArray in the parametertargetArray in array1. This will be our reference array which we will compare with each 1-dimensional array in targetArraytargetArrayand compare it with array1array1, return falsetrueHope this helps.
You can use Stream API and Arrays#equals to write elegant 1 line checkIdentical:
public static boolean checkIdentical(int[][] targetArray) {
return Stream.of(targetArray).allMatch(elm -> Arrays.equals(targetArray[0], elm));
}