找出2个数组长度的最大值

Find the maximum of the length of 2 arrays

我将 2 个不同长度的数组传递给控制器​​,我想执行一个 for 循环,其长度将是 2 个数组长度的最大值。 我不知道如何执行。我试过 Math.max 但它给了我错误,因为无法为最终变量长度赋值。

String[] x =0;
x.length = Math.max(y.length,z.length);
for(int i=0; i < x.length; i++)

x和y的元素个数不固定。它改变了我们从前端传递的内容。

用所需长度初始化新数组:

String[] x = new String[Math.max(y.length,z.length)];

如果您不需要创建数组,只需使用 Math.max 的结果作为停止循环的条件:

for (int i = 0; i < Math.max(y.length,z.length); i++) {
    //...
}

只需将您的 Math.max() 操作带入数组的初始化即可。

String[] x = new String[Math.max(y.length, z.length)];

为清楚起见,这里有一个扩展:

int xLength = Math.max(y.length, z.length);
String[] x = new String[xLength];

编辑:除非,OP,您对创建另一个数组不感兴趣...

I want to execute a for loop and length of that will be the max of the length of 2 arrays

只需将您的 Math.max() 操作带入您的 for 循环:

for(int i=0; i < Math.max(y.length, z.length); i++){
    //code here
}
int max_length = Math.max(y.length,z.length);

for(int i=0; i < max_length ; i++){
 //...
}

如果您尝试创建一个总长度为 y and z arrays 的数组,例如

,您可以使用 max_length 创建一个新的 String[]
String[] newArray = new String[max_length];

将变量设置为数组的最大长度,创建一个具有该长度的新数组,然后循环直到该点。

int maxLen = Math.max(y.length, x.length);
String[] array = new String[maxLen];
for(int i = 0; i < maxLen; i++){
    // Loop code here
}