I was under the impression that creating a variable and setting it equal to an object would act as a reference, ie. changing the original object would subsequently "change" the variable as well. The code i'm specifically referring to is as follows:
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
...
ListNode l1 = ... // l1 is an input
ListNode iterator = head; // copying l1 into a new list, starting with 'head'
...
iterator.next = l1;
l1 = l1.next;
The last piece of code loops multiple times. Why is it that, when we set iterator.next = l1
, it acts as copying the 'l1' object, instead of creating a reference to l1? Shouldn't the result just be a bunch of copies of l1, rather than at each step of the way?