Java method with unlimited arguments

后端 未结 2 1032
面向向阳花
面向向阳花 2020-12-04 21:36

The spring framework uses methods where you can pass as many arguments as you like.

I would like to write a function that can also take an unlimited amount of data.

相关标签:
2条回答
  • To add the Bozho's answer, you can also have other arguments in your method before varargs:

    // foo(13, "foo", "bar", "baz");
    // will print:
    // 13 - |foo||bar||baz|
    public void foo(int a, String... b) {
        System.out.println(a + " - ");
    
        for (String c : b) {
            System.out.print("|" + c + "|");
        }
    }
    

    However you can not have arguments of a different type after. These do not work:

    public void bar(String... b, int b);
    public void foo(int a, String... b, int b);
    
    0 讨论(0)
  • 2020-12-04 22:04

    It's called varargs.

    It allows a method to take any number of arguments. They are accessible as an array in the method:

    public void foo(String... args) {
        for (String arg : args) {
          // do smth with arg.
         }
    }
    

    This is syntactic sugar. The compiler hides the array creation, so instead of

     bar.foo(new String[] {"1", "2", "3"});
    

    you write

     bar.foo("1", "2", "3");
    
    0 讨论(0)
提交回复
热议问题