Notice: With the launch of Adobe Cookbooks, this site will no longer be accepting new entries or posting new content. Thanks to everyone who submitted content!

How can you test to see if two arrays are the same?

CF does not offer an easy way to compare two single dimension arrays. The most common solution involving looping through one array and comparing each item to the second array. It is a complicated and messy solution.

Actually there's a very simple way of comparing two arrays using CF's underlying java. According to a recent blog by Rupesh Kumar of Adobe (http://coldfused.blogspot.com/), ColdFusion arrays are an implementation of java lists (java.util.List). So all the Java list methods are available for CF arrays.

So to compare 2 arrays all you need to do is use the equals method. It returns a YES if the arrays are equal and NO if they are not.

For example, given these arrays:

<cfset array1 = listToArray("tom,dick,harry,phred")/>
<cfset array2 = listToArray("dick,harry,phred") />
<cfset array3 = listToArray("tom,dick,harry,phred")/>

To test for equality:

<cfoutput>
Array2 equals Array1 #array2.equals(array1)# (returns a NO) <br/>
Array3 equals Array1 #array3.equals(array1)# (returns a YES) <br/>
</cfoutput>


This question was written by Larry C. Lyons.
It was last updated on July 21, 2008 at 9:30:28 AM EDT.

CFML Referenced

<cfoutput>

Categories

Data Structures

Comments

Comment made by Thomas Case on July 21, 2008 at 11:39 AM
One correction to your note: ColdFusion arrays are an implementation of Java's "ArrayList," which inherits the equals method from the AbstractList class. The java.util.List interface does not define an "equals" method.


Comment made by radekg on July 21, 2008 at 12:42 PM
@Thomas: <cfset arr1 = arrayNew(1) /> createObject("java","java.util.ArrayList").getClass(). isAssignableFrom(arr1.getClass())

returns NO so CF arrays are not java.util.ArrayList. They're just made to look like ArrayList.


Comment made by Larry C. Lyons on July 22, 2008 at 2:17 PM
@Thomas:

Please note: http://java.sun.com/javase/6/docs/api/java/util/List.html#equals(java.lang.Object) the api for java.util.List discusses the equals method.