2011-05-18 69 views
2

我想知道是否有办法做到它在标题中所说的内容。作为一个例子,我有下面的代码:有没有办法改变这个关键字引用的对象?

public List<Shape> path() { 
    List<Shape> path = new ArrayList<Shape>(); 
    path.add(0, this); 
    while (this.parent != null) { 
     path.add(0, this.parent); 
     this = this.parent; 
    } 
    return path; 
} 

我想找到这样做this = this.parent这样我就可以不断增加的parents到ArrayList,直到不再有父母的合法途径。可能吗?

谢谢。

+4

为什么不使用局部变量而不是'this'? – 2011-05-18 11:47:18

回答

4

不,这是不可能的。 this绑定到当前对象,但是没有人会阻止您使用其他引用名称,例如currentNode或任何首先初始化为thiscurrentNode = this)的内容,然后将其父项指定给它:currentNode = currentNode.parent

+0

谢谢。这解决了它。 – Jigglypuff 2011-05-18 12:03:59

2

您可以更改由this引用的对象的状态,

但你不能让this指向其他对象,

thisfinal

对于你的情况可以创建本地参考并对其进行操作

1

this分配给while之前的正确类型的变量并使用该变量。

public List<Shape> path() { 
    List<Shape> path = new ArrayList<Shape>(); 
    path.add(0, this); 

    SomeVar node = this; 

    while (node.parent != null) { 
     path.add(0, node.parent); 
     node = node.parent; 
    } 
    return path; 
} 
相关问题