When do you use varargs in Java?

后端 未结 8 1754
猫巷女王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);
    
    0 讨论(0)
  • 2020-11-22 05:54

    In Java doc of Var-Args it is quite clear the usage of var args:

    http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

    about usage it says:

    "So when should you use varargs? As a client, you should take advantage of them whenever the API offers them. Important uses in core APIs include reflection, message formatting, and the new printf facility. As an API designer, you should use them sparingly, only when the benefit is truly compelling. Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "

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