How do I swap the reference in Java? (It seems much easier in C++)


  • 0
    X

    I encounter with the problem when I write a function in Java, I will explain the problem in a easier format:

    My intention is to let the aNode reference in the parameter points to bNode and bNode reference in the parameter points to aNode.

    If I write the code in C++,I can use

    boolean swap(Node** aNode,Node** bNode)
    {
        Node** tempNode = null;
        *tempNode = *aNode;
        *aNode = *bNode;
        *bNode = *tempNode;
        return true;
    }
    

    to achieve the effect

    But I want to achieve it in Java,how can I do? The following code won't work and I konw the reference will back to the original source when we come out of the function. So how can we modify the reference in Java?

    public static boolean swap(Node aNode,Node bNode)
    {
    	Node tempNode = null;
    	tempNode = aNode;
    	aNode = bNode;
    	bNode = tempNode;
    	return true;
    }

  • 0
    A
    tempNode=aNode.next;
    aNode.next=bNode.next;
    bNode.next=tempNode;
    return true;
    

    You change the objects of which the reference is passed in the function. So if I modify the object to which the passed reference is pointing I can change the actual contents.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.