I wrote this test,
public class test {
public static String[] foo(String[] myArray, int index) {
myArray[index] = "world";
return myArray;
}
public static void main(String[] args) {
String[] fooArray = new String[10];
for (int i = 0; i < 10; i ++) {
fooArray[i] = "hello";
}
foo(fooArray, 9);
for (int i = 0; i < 10; i ++) {
System.out.println(fooArray[i]);
}
}
}
which results in this output
hello
hello
hello
hello
hello
hello
hello
hello
hello
world
So foo
basically just changes a value in the array and returns this modified array. But the actual fooArray
is being modified by the foo
method (as evidenced by the output). Is there an efficient way to pass the array fooArray
and have it not modified by foo
?
I know that I could make a copy of the fooArray
in the method like
public String[] void foo(String[] myArray, int index) {
String[] copy = new String[];
for (int i = 0; i < 10; i ++) {
copy[i] = myArray[i];
}
copy[index] = "world";
return copy;
}
but I am planning to do this modification on arrays of a size in the thousands and also I am planning to this millions (or even billions) of times during runtime so I don't think that copying the entire array every time would be an efficient solution (I need to get a reasonable runtime).