有没有办法改变 this 关键字引用的对象?

发布于 2024-11-08 00:47:17 字数 425 浏览 0 评论 0原文

我想知道是否有办法做到标题中所说的。作为一个例子,我有下面的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

尾戒 2024-11-15 00:47:17

不,这是不可能的。 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 like currentNode or whatever that you first initialize as this (currentNode = this) and then assign the parents to it: currentNode = currentNode.parent.

三月梨花 2024-11-15 00:47:17

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

但您不能使 this 指向其他对象,

thisfinal

对于您的情况,您可以创建本地引用并对其进行操作

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 is final

For your case you can create a local reference and operate on it

似最初 2024-11-15 00:47:17

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

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;
} 

Assing this to variable of the correct type before the while and use that variable.

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;
} 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文