有没有办法改变 this 关键字引用的对象?
我想知道是否有办法做到标题中所说的。作为一个例子,我有下面的代码:
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
添加到数组列表中,直到有不再有父母。是否可以?
谢谢。
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. Is it possible?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,这是不可能的。
this
绑定到当前对象,但没有人阻止您使用其他引用名称,例如currentNode
或您首先初始化为this
的任何名称(< code>currentNode = this),然后为其分配父级:currentNode = currentNode.parent
。No, it's not possible.
this
is bound to the current object, but nobody stops you from using other reference names likecurrentNode
or whatever that you first initialize asthis
(currentNode = this
) and then assign the parents to it:currentNode = currentNode.parent
.您可以更改
this
引用的对象的状态,但您不能使
this
指向其他对象,this
是final
对于您的情况,您可以创建本地引用并对其进行操作
You can change the state of the object which is referred by
this
,But you can't make
this
point to some other object,this
isfinal
For your case you can create a local reference and operate on it
在
while
之前将this
赋给正确类型的变量并使用该变量。Assing
this
to variable of the correct type before thewhile
and use that variable.