我有两个String
数组,假设:
String[] s1 = {"a","b","c"}
String[] s2 = {"c","a","b"}
//这些数组应该相等
我想以“最干净”的方式检查它们的相等性。
我尝试使用Arrays.equals(s1,s2)
,但得到的答案是错误的。我猜这个方法关心元素的顺序,我不想让它变得重要。
你能告诉我怎样才能用好的方式做到这一点吗?
发布于 2012-04-14 22:31:12
其他人则建议对数组进行排序。但是既然你在寻找“最干净”的解决方案,我认为原始的数组不应该被修改。因此:
List<String> l1 = new ArrayList<String>(Arrays.asList(s1));
List<String> l2 = new ArrayList<String>(Arrays.asList(s2));
Collections.sort(l1);
Collections.sort(l2);
boolean outcome = l1.equals(l2);
发布于 2012-09-06 23:44:35
如果您使用的是Eclipse Collections,则可以使用Bag
来确定这两个数组是否相等。
String[] s1 = {"a", "b", "c", "c"};
String[] s2 = {"c", "a", "b", "c"};
Bag<String> h1 = Bags.mutable.with(s1);
Bag<String> h2 = Bags.mutable.with(s2);
Assert.assertEquals(h1, h2);
如果包(也称为多集)在每个元素中出现的次数相同,则它们被视为相等。顺序并不重要,它可以正确地处理重复的元素。使用有哈希表支持的包的优点是创建一个包需要线性时间。这两种排序都需要O(n log n)。
注意:我是Eclipse Collections的提交者
发布于 2012-04-14 22:27:00
String[] s1 = {"a","b","c"};
String[] s2 = {"b","c","a"} ;
Arrays.sort(s1);
Arrays.sort(s2);
if(Arrays.equals(s1, s2)){
System.out.println("ok");
}
https://stackoverflow.com/questions/10154305
复制相似问题