有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java查找2个数组的最大长度

我将两个不同长度的数组传递给控制器,我想执行一个for循环,其中的长度将是两个数组长度的最大值。 我不知道该怎么做。我试过数学。但它给我的错误是无法为最终变量长度赋值

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

x和y中元素的数量不是固定的。它改变了我们从前端传递的信息


共 (4) 个答案

  1. # 1 楼答案

    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];
    
  2. # 2 楼答案

    只需将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];
    

    编辑:除非你对创建另一个数组不感兴趣

    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
    }
    
  3. # 3 楼答案

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

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

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

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

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

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