I'm new to Java and currently playing around with ArrayLists. I found something I couldn't quite grasp and couldn't find a previous post that answered my question. I was having problems understanding why I can't overwrite an entire ArrayList
with another ArrayList
. I've found that replacing each item in an ArrayList
works, which I can quite understand. However, I can't seem to grasp why I can't replace the content of an ArrayList
entirely.
For example:
class Test {
public static void switchArrLists(ArrayList<Integer> x, ArrayList<Integer> y) {
ArrayList<Integer> temp = x;
x = y;
y = temp;
System.out.println("x is: " + x);
System.out.println("y is: " + y);
}
public static void main(String[] args) {
ArrayList<Integer> x = new ArrayList<Integer>(Arrays.asList(5, 0, 20, 4, 0, 0, 9));
ArrayList<Integer> y = new ArrayList<Integer>(Arrays.asList(0, 4, 10, 9, 6, 12, 4));
switchArrLists(x, y);
System.out.println("x is: " + x);
System.out.println("y is: " + y);
}
}
When the code runs, I've found that the result is the following:
x is: [0, 4, 10, 9, 6, 12, 4]
y is: [5, 0, 20, 4, 0, 0, 9]
x is: [5, 0, 20, 4, 0, 0, 9]
y is: [0, 4, 10, 9, 6, 12, 4]
which shows that the switchArrLists method doesn't really work. I was wondering why this would be the case. I have a feeling that it has to do something with reference values but can't really understand it completely.