I am confused with something about String arrays. If I change the array in a method and access it within the method, it stays changed, but if I use the method to change it, then access it right after, it doesn't work.
public class ArrayTester{
public static void main(String[] args){
String[] names = {"Jim", "Gary", "Bob"};
printMe(names);
remove(1, names);
printMe(names);
}
printMe(String[] array){
for(String str : array){
System.out.print(str + " ");
}
System.out.println();
}
remove(int pos, String[] array){
array2 = new String[array.length - 1];
for(int i = 0; i < pos; i++){
array2[i] = array[i];
}
for(int i = pos; i < array2.length - 1; i++){
array2[i] = array[i + 1];
}
array = array2;
//printMe(array); <-- works with printMe here, but not in the
// main method
}
}
I expect the result to look like "Jim Gary Bob" and then "Jim Bob" Unfortunately, I get "Jim Gary Bob" twice. However, if I put printMe in the remove method instead of in the main method, I get "Jim Gary Bob" and then "Jim Bob" I'm not sure why it is and I suspect it's got something to do with the way the array is stored, but I can't figure it out.