数组等于忽略顺序 [英] Arrays Equals Ignoring Order
问题描述
可能重复:
Java:检查数组的相等性(顺序无关紧要)
我有两个数组:
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.
我试过 Arrays.equals(a1,a2)
但是它考虑了元件。
org.apache.commons.lang.ArrayUtils
不提供这个东西。
I tried Arrays.equals(a1, a2)
but it considers order of element.
org.apache.commons.lang.ArrayUtils
does not provide this thing.
我知道我可以通过创建我自己的方法(检查相同的长度,然后排序两个数组,然后使用 Arrays.equals(a1,a2)
)来实现相同的目的,但想知道这是否在任何API中提供的东西或有更聪明的方法来做同样的事情。
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.
推荐答案
如果你有这些数组继承的东西从Collection中,您可以从Collection界面中使用 collection.containsAll(otherCollection)
。但是,您还需要比较两者的长度以验证一组不是另一组的超集。
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.
(感谢Aardvarkk和piegames 。)
(Thanks go to Aardvarkk and piegames.)
http://docs.oracle.com/javase/6/docs/api/java/util/Collection.html#containsAll(java.util.Collection)
注意:这将达到一定程度。这被定义为检查现有的任何元素的至少一个。也就是说,如果一个集合中有3 a
值,另一个集合中有7 a
值,那么 not 必然会导致它们将它们称为不相等。
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.
示例:
[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
这篇关于数组等于忽略顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!