假设某一对象的一个引用是A,如果想要在子函数f()里修改引用的值怎么办?不是修改A所指
对象的值,不使用全局变量。
感觉说的不清楚,上代码:
先是正确代码:
public class Solution {
TreeNode listTail = null;
public void inorder(TreeNode root){
if(root == null) return;
if(root.left != null){
inorder(root.left);
}
root.left = listTail;
if(listTail != null){
listTail.right = root;
}
listTail = root;
if(root.right != null){
inorder(root.right);
}
}
public TreeNode Convert(TreeNode root) {
if(root == null) return null;
inorder(root);
TreeNode head = listTail;
while(head.left != null){
head = head.left;
}
return head;
}
}
然后是错误代码:
public class Solution {
public void inorder(TreeNode root, TreeNode listTail){
if(root == null) return;
if(root.left != null){
inorder(root.left,listTail);
}
root.left = listTail;
if(listTail != null){
listTail.right = root;
}
listTail = root;
if(root.right != null){
inorder(root.right,listTail);
}
}
public TreeNode Convert(TreeNode root) {
if(root == null) return null;
TreeNode head = null;
inorder(root,head);
while(head != null && head.left != null){
head = head.left;
}
return head;
}
}
如果我想像错误代码那样写,调用这种形式的函数public void inorder(TreeNode root, TreeNode listTail,然后在函数内部修改listTial本身而不是其指向的对象,应该怎么做,但是不要用正确代码里使用成员变量的方法
首先,Java没有子函数的概念,函数就是类的成员方法。
其次,你想在这个类的成员函数f里面修改引用的值是什么意思,是修改这个引用A的指针地址呢,还是修改A的属性的值呢?
如果是想改变A的引用地址的话,直接重新赋值新的指针给这个A成员遍历就可以了。
一个方法是不能让对象参数引用一个新的对象的
不知道装饰器模式可以满足你这个要求么,装饰器模式就是通过保持对一个对象的引用,增加额外的功能,但是实际上并不是真的修改了对象http://blog.csdn.net/zzhao114/article/details/54646808