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>

5 Responses to Passing ColdFusion Arrays to Java

  1. PaulH says:

    great, but are java.util.Arrays one dimensional arrays, the java docs only refer to []??

  2. Sam says:

    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

  3. PaulH says:

    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.

  4. NStarer says:

    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?

  5. scott says:

    On synchronization, would around the Java call help?