reference

public class Reference {
public void setTreeNode(TreeNode n) {
n = new TreeNode(2);
}

public void setTreeValue(TreeNode n) {
n.val = 3;
}

public static void main(String args[]) {
Reference r = new Reference();
TreeNode root = new TreeNode(1);
r.setTreeNode(root);
System.out.println( root.val ); // output => 1

r.setTreeValue(root);
System.out.println( root.val ); // output => 3
}
}

in the method of setTreeNode, a copy of root reference is passed to n, that means, n has root’s reference, and this reference is pointed to root, however, after   n = new TreeNode(2);, n a value of reference which pointed to another object. The pointer value is changed, but the value inside of two nodes are not changed.

in the method of setTreeValue, n is pointed to root, so the root’s value is changed.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s