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>