确保多个数组长度相同的最佳方法

Gen*_* S. 2 java arrays

由于我不想进入的原因,我有一堆并行数组,我很好奇最优雅的方法是确保它们的长度都相同.(如果其中一个长度错误,则必须缺少数据并且数组将无法正确对齐).

我不喜欢这样做的想法......

if(array1.length != array2.length || array1.length != array3.length etc...)
Run Code Online (Sandbox Code Playgroud)

这看起来很可怕,我真的希望有更优雅的方式......

我的冲动是将它们的长度加在一起并除以数组的总数,看看这个数字是否与数组长度相同,但我愿意接受建议(以及被告知我的想法赢了'因某些我忽略的原因而工作.

我是Java,但我怀疑这个问题的答案是语言无关.

Joa*_*uer 6

您可以编写这样的方法(使用java.lang.reflect.Array):

 import java.lang.reflect.Array;

 /**
  * Checks an arbitrary number of parallel arrays to verify that they have the same length.
  * @throws IllegalArgumentException if any of the arguments is not an array or if the lengths of the arrays are not equal.
  */
 public static void checkParallelArrays(Object... arrays) {
   if (arrays.length < 1) {
     return;
   }
   int expectedLength = Array.getLength(arrays[0]);
   for (int i=1; i<arrays.length; i++) {
     int length = Array.getLength(arrays[i]);
     if (length != expectedLength) {
       throw new IllegalArgumentException("Array " + i + " doesn't have expected length " + expectedLength + ": " + length);
     }
   }
 }
Run Code Online (Sandbox Code Playgroud)

需要注意的是参数类型是Object允许本原阵列(int[],char[],...),以及.如果您可以将参数限制为仅引用类型数组,那么这将简化代码.