I need to write a private method in java that receives 2 arrays. is there a way to make that they have to be the same length?
something like:
public static void method(int[] arr1 , int[] arr2[arr1.length])
CodePudding user response:
Not in the method's signature and not at compile time. But we can validate the lengths in the method's body and, for example, throw an IllegalArgumentException if they do not match:
public static void method(int[] arr1 , int[] arr2) {
if (arr1.length != arr2.length) {
throw new IllegalArgumentException("arrays \"arr1\" and \"arr2\" must have same length.");
}
...
}
CodePudding user response:
If you can use the Apache Commons Lang3 library, it provides a way via ArrayUtils.isSameLength():
import org.apache.commons.lang3.ArrayUtils;
// ...
private static void method(int[] arr1, int[] arr2) {
if (!ArrayUtils.isSameLength(arr1, arr2)) {
throw new IllegalArgumentException("Arrays must be same length");
}
// ...
}
This does have the quirk, like many other methods of the class, of treating a null argument the same as a 0-length array instead of raising a NullPointerException. May or may not be desirable depending on what you're doing.
