I've grown acostumed to use c++ pass by reference and now I'm starting to code more in Java. When solving a problem at leetcode I faced a problem: I tried to use this piece of code so I didn't have to rewrite this three lines often.
public void copyAndMoveNodes(ListNode tail, ListNode nodeToCopy) {
tail.next = new ListNode(nodeToCopy.val);
tail = tail.next;
nodeToCopy = nodeToCopy.next;
}
I was expecting it to work similarly this in c++:
void copyAndMoveNodes(ListNode* &tail, ListNode* &nodeToCopy) {
ListNode newNode = new ListNode(nodeToCopy.val);
tail->next = &newNode;
tail = tail->next;
nodeToCopy = nodeToCopy->next;
}
But I discovered I passed just the copy of the objects' references in java as writen in the first piece of code.
Is it possible to rewrite this in Java to work similarly? I use this sequence of three commands many times and I don't want to write them every time, it makes the code more confusing.