有没有办法改变这个关键字引用的对象?
问题描述:
我想知道是否有办法做到它在标题中所说的内容。作为一个例子,我有下面的代码:有没有办法改变这个关键字引用的对象?
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,直到不再有父母的合法途径。可能吗?
谢谢。
答
不,这是不可能的。 this
绑定到当前对象,但是没有人会阻止您使用其他引用名称,例如currentNode
或任何首先初始化为this
(currentNode = this
)的内容,然后将其父项指定给它:currentNode = currentNode.parent
。
+0
谢谢。这解决了它。 – Jigglypuff 2011-05-18 12:03:59
答
您可以更改由this
引用的对象的状态,
但你不能让this
指向其他对象,
this
是final
对于你的情况可以创建本地参考并对其进行操作
答
将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;
}
为什么不使用局部变量而不是'this'? – 2011-05-18 11:47:18