java: how can i create a function that supports any number of parameters?

后端 未结 3 1191
栀梦
栀梦 2020-12-03 20:35

is it possible to create a function in java that supports any number of parameters and then to be able to iterate through each of the parameter provided to the function ?

相关标签:
3条回答
  • 2020-12-03 21:11

    Yes, using varargs.

    0 讨论(0)
  • 2020-12-03 21:18

    Java has had varargs since Java 1.5 (released September 2004).

    A simple example looks like this...

    public void func(String ... strings) {
        for (String s : strings)
             System.out.println(s);
    }
    

    Note that if you wanted to require that some minimal number of arguments has to be passed to a function, while still allowing for variable arguments, you should do something like this. For example, if you had a function that needed at least one string, and then a variable length argument list:

    public void func2(String s1, String ... strings) {
    
    }
    
    0 讨论(0)
  • 2020-12-03 21:23

    As other have pointed out you can use Varargs:

    void myMethod(Object... args) 
    

    This is actually equivalent to:

    void myMethod(Object[] args) 
    

    In fact the compiler converts the first form to the second - there is no difference in byte code. All arguments must be of the same type, so if you want to use arguments with different types you need to use an Object type and do the necessary casting.

    0 讨论(0)
提交回复
热议问题