x.509
x.509

Reputation: 2235

Java Code - Why a variable is being cloned here?

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?

Upvotes: 1

Views: 108

Answers (2)

jjnguy
jjnguy

Reputation: 138932

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.

Upvotes: 6

codymanix
codymanix

Reputation: 29508

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

Upvotes: 2

Related Questions