java有没有办法写一个方法来获取2个长度必须相同的数组?

Is there a way in java to write a method that gets 2 arrays that must be the same length?

我需要在 java 中编写一个私有方法来接收 2 个数组。 有没有办法让它们的长度必须相同?

类似于:

public static void 方法(int[] arr1 , int[] arr2[arr1.length])

不在方法的签名中,也不在编译时。但是我们可以验证方法主体中的长度,例如,如果它们不匹配,则抛出 IllegalArgumentException

public static void method(int[] arr1 , int[] arr2) {
    if (arr1.length != arr2.length) { 
        throw new IllegalArgumentException("arrays \"arr1\" and \"arr2\" must have same length."); 
    }
    ...
}

如果您可以使用 Apache Commons Lang3 库,它提供 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");
    }
    // ...
}

这确实有一个怪癖,就像 class 的许多其他方法一样,将 null 参数视为与 0 长度数组相同,而不是引发 NullPointerException。可能需要也可能不需要,具体取决于您在做什么。