如果实例变量设置为 final,则其值不能更改,例如
public class Final {
private final int b;
Final(int b) {
this.b = b;
}
int getFinal() {
return b = 8; // COMPILE TIME ERROR
}
}
在代码中的某处,我看到实例类变量 HashMap 声明为 final
private final Map<String, Object> cacheMap = new HashMap<String, Object>();
我不明白为什么会这样宣布?通常在这种情况下它被声明。这是否意味着一旦我放入哈希映射,我就无法改变它的值?
编辑:
如果声明为 final 的 cacheMap 作为参数传递给另一个类,那么如果我更改其引用,则不会为 final 显示错误。为什么会这样?
class CacheDTO {
private Map conditionMap;
public Map getConditionMap() {
return conditionMap;
}
public void setConditionMap(Map conditionMap) {
this.conditionMap = conditionMap;
}
}
然后
private final Map<String, Object> cacheMap = new HashMap<String, Object>();
CacheDTO cc = new CacheDTO();
cc.setConditionMap(cacheMap);
Map<String, Object> cacheMapDeclaredAsFinal = cc.getConditionMap();
Map<String, Object> newMap = new HashMap<String, Object>();
cacheMapDeclaredAsFinal = newMap; // In this case no error is shown. Though cacheMapDeclaredAsFinal reference is obtained by calling cc.getConditionMap() and cacheMapDeclaredAsFinal refers to final.