How to pass varargs by reference in Java

前端 未结 6 1277
青春惊慌失措
青春惊慌失措 2021-01-29 03:53

I\'m writing a method that receives any number of arguments and returns them modified. I have tried with varargs but it doesn\'t work, here you can see a simplified version of t

6条回答
  •  花落未央
    2021-01-29 04:49

    An array of String[] can be passed to fulfill the vararg requirement - no copy/clone of the array passed as such is made so mutating the array inside .. well, changes that array everywhere. But this is ugly, particularly because it adds a "side-effect, sometimes".

    However, you cannot do "by reference"1 otherwise as a new array is created when arguments are passed normally to a variadic method as in the original code.

    // but avoid code like this, if possible
    String[] words = {"hello", "world"};
    addPrefix(words);
    System.out.println("hello: " + words[0] + "  world: " + words[1]);
    

    1 It's only Call by Reference if rebinding a parameter changes a binding in the caller, which Java does not support. It doesn't matter if varargs are used or not.

提交回复
热议问题