How to pass varargs by reference in Java

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

    Java is pass by value. You cannot achieve what you wish. Instead you can return the modified array from addPrefix() function.

    public static void main(String args[]) {
    
        String hello = "hello";
        String world = "world";
    
        String[] elements = addPrefix(hello, world);
    
        for (int i = 0; i < elements.length; i++) {
            System.out.println(elements[i]);
        }
    
    
    
    
    }
    
    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;
    }
    

    and output

    prefix_hello
    prefix_world
    prefix_hello
    prefix_world
    

提交回复
热议问题