Arrays Equals Ignoring Order

Anil Bharadia picture Anil Bharadia · Aug 17, 2012 · Viewed 42.5k times · Source

Possible Duplicate:
Java: Checking equality of arrays (order doesnt matter)

I have two arrays :

String[] a1 = {"a", "b", "c"};
String[] a2 = {"c", "b", "a"};

I need to check if both contains same elements (and of same length) irrespective of order of elements.

I tried Arrays.equals(a1, a2) but it considers order of element. org.apache.commons.lang.ArrayUtils does not provide this thing.

I know I can achieve the same by creating my own method (checking for same length, then sorting both array and then using Arrays.equals(a1, a2)) but wanted to know if this thing is provided in any API or there is more smart way to do the same.

Answer

BlackVegetable picture BlackVegetable · Aug 17, 2012

If you have these arrays in something inheriting from Collection, you can just use collection.containsAll( otherCollection ) from the Collection interface. However, you'll also need to compare the lengths of the two to verify that one set isn't a superset of the other.

(Thanks go to Aardvarkk and piegames.)

http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#containsAll(java.util.Collection)

Note: This will work up to a point. This is defined to check for at least one of any element existing. That is, if you have 3 a values in one collection, and 7 a values in the other, that will not necessarily cause it to call them unequal.

Examples:

[a, b, c] == [c, a, b]             // Works -- Mixed order
[a, b, c, d, d] == [a, b, d, c, d] // Works -- Mixed order with repeats
[a, b, c, d, d] == [a, b, b, c, d] // FAILS -- Different repeats
[a, b, c, d, d] != [a, b, c, d]    // Works -- Length differs with repeats
[a, b, c, d] != [a, b, c]          // Works -- Length differs
[a, b, d] != [a, b, c]             // Works -- Disjoint sets