Java “params” in method signature?

前端 未结 3 1652
无人及你
无人及你 2020-11-29 02:49

In C#, if you want a method to have an indeterminate number of parameters, you can make the final parameter in the method signature a params so that the method

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 03:04

    In Java it's called varargs, and the syntax looks like a regular parameter, but with an ellipsis ("...") after the type:

    public void foo(Object... bar) {
        for (Object baz : bar) {
            System.out.println(baz.toString());
        }
    }
    

    The vararg parameter must always be the last parameter in the method signature, and is accessed as if you received an array of that type (e.g. Object[] in this case).

提交回复
热议问题