开发者

Java Code - Why a variable is being cloned here?

开发者 https://www.devze.com 2023-01-25 07:34 出处:网络
Look at the following code which i am copying from javax.naming.InitialContext. An argument of HashTable type is being passed to the constructor. here is the code snippet

Look at the following code which i am copying from javax.naming.InitialContext. An argument of HashTable type is being passed to the constructor. here is the code snippet

public InitialContext(Hashtable<?,?> environment) throws NamingException
{
    if (environment != null) {
        environment = (Hashtable)environment.clone();
    }
    init(environment);
}

My question is, why environment is being cloned here when it could have been passed directly to init method?开发者_运维技巧


This code is protecting itself from an external caller changing the state of the HashTable.

By making a clone of it, they ensure that changes made to the Hashtable that was passed in are not reflected inside of the method/object the table was passed into.

A short example using arrays:

//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.

That vulnerability can be avoided by making a copy of the array. Changes to the original array will not show up in the copy.


Because it could be changed from the outside of this method?

0

精彩评论

暂无评论...
验证码 换一张
取 消