How to pass varargs by reference in Java

前端 未结 6 1273
青春惊慌失措
青春惊慌失措 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:34

    This is a classic example of how many people dont know the way in which varargs works. Varargs is simply a holder for an array which is created when the methods with varargs parameter is invoked. To make my point clearer,we must have a look at the bytecode of varargs:-

    Your code this

    String hello = "hello";
    String world = "world";
    addPrefix(hello, world);
    

    becomes to this

    addPrefix(new String[]{hello, world});

    Since you do not have reference to your newly created array,you are simply printing the values of your original String objects ,hello and world

    You need to explicity return the array reference and iterate over it to view the changes

    public static String[] addPrefix(String... elements) {
       for (int i = 0; i < elements.length; i++) {
          elements[i] = "prefix_" + elements[i];
       }
    
       for (int i = 0; i < elements.length; i++) {
          System.out.println(elements[i]);
       }
      return elements;
    }
    

提交回复
热议问题