[英]Is there a way to change the object the this keyword refers to?
I was wondering if there was a way to do what it says in the title. 我想知道是否有办法做到标题中所说的。 As an example I have code below: 例如,我有以下代码:
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;
}
I want to find a legal way of doing this = this.parent
so that I can keep adding the parents
to the arraylist until there are no more parents. 我想找到一种合法的方法来做到this = this.parent
这样我就可以继续将parents
添加到数组列表中,直到没有更多父级为止。 Is it possible? 可能吗?
Thanks. 谢谢。
No, it's not possible. 不,这是不可能的。 this
is bound to the current object, but nobody stops you from using other reference names like currentNode
or whatever that you first initialize as this
( currentNode = this
) and then assign the parents to it: currentNode = currentNode.parent
. this
被绑定到当前对象,但没有人阻止你使用像其他引用名称currentNode
或任何你先初始化为this
( currentNode = this
),然后指定父母吧: currentNode = currentNode.parent
。
You can change the state of the object which is referred by this
, 您可以更改由引用的对象的状态, this
,
But you can't make this
point to some other object, 但你不能让this
一点到其他对象,
this
is final
this
是final
For your case you can create a local reference and operate on it 对于您的情况,您可以创建本地参考并对其进行操作
Assing this
to variable of the correct type before the while
and use that variable. Assing 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.