When do you use varargs in Java?

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

    I have a varargs-related fear, too:

    If the caller passes in an explicit array to the method (as opposed to multiple parameters), you will receive a shared reference to that array.

    If you need to store this array internally, you might want to clone it first to avoid the caller being able to change it later.

     Object[] args = new Object[] { 1, 2, 3} ;
    
     varArgMethod(args);  // not varArgMethod(1,2,3);
    
     args[2] = "something else";  // this could have unexpected side-effects
    

    While this is not really different from passing in any kind of object whose state might change later, since the array is usually (in case of a call with multiple arguments instead of an array) a fresh one created by the compiler internally that you can safely use, this is certainly unexpected behaviour.

提交回复
热议问题