Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 有没有办法更改this关键字所指的对象?_Java_Oop_This - Fatal编程技术网

Java 有没有办法更改this关键字所指的对象?

Java 有没有办法更改this关键字所指的对象?,java,oop,this,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; }

我想知道是否有办法做到标题中所说的。例如,我有以下代码:

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;
}
公共列表路径(){
列表路径=新的ArrayList();
添加路径(0,该路径);
while(this.parent!=null){
添加路径(0,此.parent);
this=this.parent;
}
返回路径;
}
我想找到一种合法的方法来执行
this=this.parent
,这样我就可以继续将
父项添加到arraylist中,直到不再有父项为止。可能吗


谢谢。

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

但是你不能让这个指向其他物体

最终版本


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

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

将此分配给
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;
} 
公共列表路径(){
列表路径=新的ArrayList();
添加路径(0,该路径);
SomeVar节点=这个;
while(node.parent!=null){
添加路径(0,节点.父节点);
node=node.parent;
}
返回路径;
} 

为什么不使用局部变量而不是