Pass by Reference in coldfusion

Arrays Created as java.util.ArrayList java objects are passed by reference to the ColdFusion Functions.Normal behavior is that of pass by value in ColdFusion Functions.
[code:cf]
<cfscript>
function addElementToArray(arrObj,appendValue){
arrayAppend(arrObj,appendValue);
return;
}
function nullify(arrObj,index){
arrObj[index] = javacast("null","0");
return;
}
function nullifyArr(arrObj){
arrObj = javacast("null","0");
return;
}
function clearArray(arrObj){
arrayClear(arrObj);
}
arrayListObj = createObject("java","java.util.ArrayList").init();
arrayListObj[1]="1";
arrayListObj[2]="2";
arrayListObj[3]="3";

writeOutput("<br>Before Call To addElementToArray Fuction;");
writeDump(arrayListObj);

addElementToArray(arrayListObj,4);
addElementToArray(arrayListObj,5);
writeOutput("<br>After Call To addElementToArray Function;");
writeDump(arrayListObj);

nullify(arrayListObj,1);
nullify(arrayListObj,5);
writeOutput("<br>After Call To nullify Function;");
writeDump(arrayListObj);

nullifyArr(arrayListObj);
writeOutput("<br>After Call To nullifyArr Function;");
writeDump(arrayListObj);

clearArray(arrayListObj);
writeOutput("<br>After Call To clearArray Function;");
writeDump(arrayListObj);
</cfscript>
[/code]

Output :
Before Call To addElementToArray Fuction;

array
1 1
2 2
3 3

After Call To addElementToArray Function;

array
1 1
2 2
3 3
4 4
5 5

After Call To nullify Function;

array
1 [undefined array element] Element 1 is undefined in a Java object of type class java.util.ArrayList.
2 2
3 3
4 4
5 [undefined array element] Element 5 is undefined in a Java object of type class java.util.ArrayList.

After Call To nullifyArr Function;

array
1 [undefined array element] Element 1 is undefined in a Java object of type class java.util.ArrayList.
2 2
3 3
4 4
5 [undefined array element] Element 5 is undefined in a Java object of type class java.util.ArrayList.

After Call To clearArray Function;

array [empty]

 

Things To Notice

  • addElementToArray appends element to the the passed array object therefore object was passed by reference.
  • Call to nullify functions sets array elements as null and changes are reflected in original array.
  • Call to nullifyArr function doesn’t set the original array as null , though the array operations on java.util.ArrayList are done on the original object.
  • Call to clearArray function successfully clears all the elements in the array and the changes are reflected again passed by reference.Thus ColdFusion array functions operate as if the object was passed by reference for java.util.ArrayList.

* java.util.HashMap (ColdFusion Struct) are also passed by reference to ColdFusion Functions