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 the code:
public static void main(String[] args) {
String hello = "hello";
String world = "world";
addPrefix(hello, world);
System.out.println("hello: " + hello + " world: " + world);
}
public static void 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]);
}
}
Printed result:
prefix_hello
prefix_world
hello: hello world: world
As you can see, the values are modified correctly inside the method, but the original vars have not changed.
I have looked at many pages like here and here but it seems that Java copies the values of the vars to an Object[]
, so the references are lost.
Any idea of how could I do it?