我想知道是否final真正"冻结"其引用,迫使其底层对象与通过不同路径对原始引用进行的任何重新分配共存,例如
class ThingHolder{
Thing thing;
}
class Thing{
int i=5;
Thing(int i){
this.i=i;
}
}
public static void main(String[] args){
ThingHolder thingHolder = new ThingHolder();
thingHolder.thing = new Thing(5);
final Thing aFinalReference = thingHolder.thing;
thingHolder.thing = new Thing(6); //will this now coexist with "aFinalReference"?
//...
}
Run Code Online (Sandbox Code Playgroud)
aFinalReference现在将作为独立对象持续存在,尽管不再是其中的一部分thingHolder,并且继续引用原始的Thing(即int当前为5的那个),不管现在发生了thingHolder什么?
所有这一切final 真正意味着,一旦你分配aFinalReference,你就无法重新分配它.
要回答您将参考什么的问题,我们将逐步介绍代码:
public static void main(String[] args){
ThingHolder thingHolder = new ThingHolder();
// create a new Thing (we'll call it "Thing5"),
// and point thingHolder.thing at it
thingHolder.thing = new Thing(5);
// thingHolder.thing now points to Thing5
final Thing aFinalReference = thingHolder.thing;
// aFinalReference now ALSO points to Thing5
// create a new Thing (we'll call it "Thing6"),
// and point thingHolder.thing at it
thingHolder.thing = new Thing(6);
// thingHolder.thing now points at Thing6 instead of Thing5
// aFinalReference, however, still points at Thing5
}
Run Code Online (Sandbox Code Playgroud)
结束时main():
thingHolder.thing 将指向"Thing6"aFinalReference 会指向"Thing5"| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |