When do you use varargs in Java?

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

    Varargs can be used when we are unsure about the number of arguments to be passed in a method. It creates an array of parameters of unspecified length in the background and such a parameter can be treated as an array in runtime.

    If we have a method which is overloaded to accept different number of parameters, then instead of overloading the method different times, we can simply use varargs concept.

    Also when the parameters' type is going to vary then using "Object...test" will simplify the code a lot.

    For example:

    public int calculate(int...list) {
        int sum = 0;
        for (int item : list) {
            sum += item;
        }
        return sum;
    }
    

    Here indirectly an array of int type (list) is passed as parameter and is treated as an array in the code.

    For a better understanding follow this link(it helped me a lot in understanding this concept clearly): http://www.javadb.com/using-varargs-in-java

    P.S: Even I was afraid of using varargs when I didn't knw abt it. But now I am used to it. As it is said: "We cling to the known, afraid of the unknown", so just use it as much as you can and you too will start liking it :)

提交回复
热议问题