« PHP Support for Pinging MXNA | Main | Macromedia Opensources Spectra »
June 26, 2003
Passing ColdFusion Arrays to Java
There were some comments on my weblog yesterday about using Java to sort ColdFusion arrays. The only problem is that you can't pass ColdFusion arrays into Java where Java is expecting an Array. Why? Because ColdFusion arrays aren't Java Arrays. They are, in fact, java.util.Vectors. Fortunately, it is easy to get an Array from a java.util.Vector. The following code demonstrates how to turn a ColdFusion array into a Java Array, and how to use Java to sort it:
<cfset cfArray = arrayNew(1)/>
<cfset cfArray[1] = "c"/>
<cfset cfArray[2] = "b"/>
<cfset cfArray[3] = "a"/>
<html>
<cfscript>
// Since CF arrays are Vectors, use toArray to turn
// them into Arrays.
jArray = cfArray.toArray();
// Iterate through the array to see that it is not sorted.
writeOutput("Unsorted...<br>");
for (i = 1; i le arrayLen(jArray); i = i + 1)
{
writeOutput(jArray[i] & "<br>");
}
// Use Java to sort the array.
Arrays = createObject("java", "java.util.Arrays");
Arrays.sort(jArray);
// Interate through the array again. It's sorted!
writeOutput("<br>Sorted...<br>");
for (i = 1; i le arrayLen(jArray); i = i + 1)
{
writeOutput(jArray[i] & "<br>");
}
</cfscript>
</html>
Posted by cantrell at June 26, 2003 11:17 AM
Comments
great, but are java.util.Arrays one dimensional arrays, the java docs only refer to []??
Posted by: PaulH at June 26, 2003 12:58 PM
ColdFusion automatically converts an CF array to a Java Array whenever a Java Array is expected. I've always just used a CF Array and passed it to Java methods without issue.
I actually do it over and over in this code sample: http://www.rewindlife.com/archives/000023.cfm
Posted by: Sam at June 27, 2003 11:48 PM
sam if java modifies the array in place, cf won't see it as the java is working on a copy of the original array.
Posted by: PaulH at June 30, 2003 2:02 PM
There is still one problem developer will have to deal with - syncronization. Because we effectively hava to copies of the same array in our hands. And the quiestion thus is how to pass array back from java to CF?
Posted by: NStarer at February 11, 2004 5:10 PM
On synchronization, would around the Java call help?
Posted by: scott at April 16, 2004 6:06 PM
Use of this website signifies your agreement to the Terms of Use and Online Privacy Policy (updated 07-14-2009).