When do you use varargs in Java?

后端 未结 8 1752
猫巷女王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:49

    Varargs are useful for any method that needs to deal with an indeterminate number of objects. One good example is String.format. The format string can accept any number of parameters, so you need a mechanism to pass in any number of objects.

    String.format("This is an integer: %d", myInt);
    String.format("This is an integer: %d and a string: %s", myInt, myString);
    

提交回复
热议问题