x.5*_*509 1 java immutability code-snippets
查看以下从javax.naming.InitialContext复制的代码.HashTable类型的参数正被传递给构造函数.这是代码片段
public InitialContext(Hashtable<?,?> environment) throws NamingException
{
if (environment != null) {
environment = (Hashtable)environment.clone();
}
init(environment);
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,为什么环境被克隆到这里可以直接传递给init方法?
这段代码保护自己免受外部调用者改变状态的影响HashTable.
通过创建clone它,它们确保对Hashtable传入的更改不会反映在传递表的方法/对象内部.
使用数组的简短示例:
//Outside code
int[] arr = new int[]{0, 1, 2, 3};
// method of class
public void init(int[] arr) {
this.arr = arr;
}
//meanwhile, in the external code
arr[0] = 42; // this change to the array will be reflected inside the object.
Run Code Online (Sandbox Code Playgroud)
通过制作数组的副本可以避免该漏洞.对原始数组的更改不会显示在副本中.