【问题标题】:How to dynamically insert unknown number of variables from a list (or array) into a method argument, in java?java - 如何在java中将列表(或数组)中未知数量的变量动态插入方法参数?
【发布时间】:2021-04-03 18:27:38
【问题描述】:

例子:

public class Example {
  public int doMath(String name, int... a) {
    System.out.println("My name is " + name);
    for (int i: a)
      int b = a+a
    return (b);
  }
  public static void main(String args[]){
    int[] testArray = new int[]{1,2,3}; //In this case size of the array is 3.
                                        // Could be any number during runtime.
    
    doMath(test[0],test[1],test[2]); //Need to insert values from into the doMath argument,
                                     // dynamically because
                                     // will not know length of array
                                     // during compile time
  }
}

我有包含对象的列表/数组,并且我将插入这些值的方法包含一个可变参数。我需要动态地将这些值插入到这个方法中,而不需要对列表的大小进行硬编码。因为在运行时,用户输入可以在 0 到 100 之间变化。而且我需要能够将此列表中的值插入到此方法中,插入到它们的正确位置。

【问题讨论】:

    标签: java arraylist methods


    【解决方案1】:

    您的代码有一些问题...

    1. 不能从静态方法调用非静态方法。
    2. 您不能声明一个局部变量(在循环内)并在范围外返回它。它的编译时错误。
    3. 仅使用数组时不需要可变参数。当您可能有一个元素数组或单个元素时,您需要可变参数。
    public class Example {
    
        // the main method can call this method
        public static int doMath(String name, int[] a) {
            System.out.println("My name is " + name);
            int b = 0;
            for (int i : a)
                b = b + i;
            return b;
        }
    
        public static void main(String args[]) {
    
            while (condition) { // just for example with a dynamic array.
                int size = 10; // you might ask user for the size of the array
    
                int[] array = new int[size];
                for (int index = 0; index < size; index++)
                    array[index] = index * 2; // you might ask user for input
                int result = doMath("math", array);
                System.out.println(result);
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答!但是,我正在处理一个预定义的函数,实际上它是一个 jdbc 模板,其中该函数实际上关心元素的位置和数量,因为它试图将数组元素值与 mysql 准备好的语句匹配。我上面给出的只是一个例子。因此,请尝试回答如何将元素值动态插入方法的参数部分的问题。
    • @spider1919 好吧,使用数组,这是动态插入参数!您可以在数组中有 N 个位置,只需对其进行迭代。你想做什么 (arg1, arg2, arg3) then (arg1, arg2) then (arg1) 只能在编译时使用可变参数,而不是在运行时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多