0

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.

user1803551
  • 12,965
  • 5
  • 47
  • 74
  • 3
    The problem that you have is that your `switch` method can't be implemented the way you think it can: assigning anything to the parameters has no effect outside of that method. And the fact that you use `ArrayList` is a red herring: the same effect would happen with `String` or `int`. See [this question](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) for an in-depth guide to what's happening and why you can't do what you want. – Joachim Sauer May 10 '23 at 22:22
  • 4
    This is not about lists, it's about references. I recommend you read about scopes. – user1803551 May 10 '23 at 22:26
  • 1
    `public static void switchArrLists(List x, List y) { List temp = new ArrayList<>(x); x.clear(); x.addAll(y); y.clear(); y.addAll(temp); }` – Elliott Frisch May 10 '23 at 23:05
  • Just as another exercise, you can make `x` and `y` fields (i.e. `private static` and not inside any method). Then use `switchArrLists()` with no parameters. See how that affects the swapping logic. – andrewJames May 10 '23 at 23:14

0 Answers0