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

时间:2011-05-18 11:45:43

标签: java oop 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添加到a​​rraylist,直到没有更多的父母为止。有可能吗?

感谢。

3 个答案:

答案 0 :(得分:4)

不,这是不可能的。 this绑定到当前对象,但是没有人阻止您使用其他引用名称,例如currentNode或您首次初始化为thiscurrentNode = this)的任何引用名称,然后分配父母:currentNode = currentNode.parent

答案 1 :(得分:2)

您可以更改this

引用的对象的状态

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

thisfinal

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

答案 2 :(得分: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;
} 
相关问题