When do you use varargs in Java?

后端 未结 8 1866
猫巷女王i
猫巷女王i 2020-11-22 04:47

I\'m afraid of varargs. I don\'t know what to use them for.

Plus, it feels dangerous to let people pass as many arguments as they want.

What\'s an example

8条回答
  •  自闭症患者
    2020-11-22 05:44

    A good rule of thumb would be:

    "Use varargs for any method (or constructor) that needs an array of T (whatever type T may be) as input".

    That will make calls to these methods easier (no need to do new T[]{...}).

    You could extend this rule to include methods with a List argument, provided that this argument is for input only (ie, the list is not modified by the method).

    Additionally, I would refrain from using f(Object... args) because its slips towards a programming way with unclear APIs.

    In terms of examples, I have used it in DesignGridLayout, where I can add several JComponents in one call:

    layout.row().grid(new JLabel("Label")).add(field1, field2, field3);
    

    In the code above the add() method is defined as add(JComponent... components).

    Finally, the implementation of such methods must take care of the fact that it may be called with an empty vararg! If you want to impose at least one argument, then you have to use an ugly trick such as:

    void f(T arg1, T... args) {...}
    

    I consider this trick ugly because the implementation of the method will be less straightforward than having just T... args in its arguments list.

    Hopes this helps clarifying the point about varargs.

提交回复
热议问题