Arrays Equals Ignoring Order [duplicate] Arrays Equals Ignoring Order [duplicate] arrays arrays

Arrays Equals Ignoring Order [duplicate]


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


i think it may work for you, sort first array with

Arrays.sort(Object[]);

and after that you can compare with

Arrays.equals(Object[],Object[]);

complete code is:

String[] a1 = {"a", "b", "c"};String[] a2 = {"c", "b", "a"};Arrays.sort(a2);boolean result= Arrays.equals(a1, a2);


Convert the lists to sets before comparing them :

new HashSet( Arrays.asList( a1 )).equals( new HashSet( Arrays.asList( a2 ) ));

Alternatively, you can sort the arrays using Arrays.sort() but that might break code which depends on the order of the elements in the arrays.