[Java教程]CollectionUtils.isEqualCollection的用法
0 2017-03-31 00:00:10
在使用Java的集合时,有些时候会需要比较两个集合是否相等,自己写方法其实也简单,但是既然有了好的实现,就不要自己造轮子了,只要了解这个轮子是什么原理就好了。public static boolean isEqualCollection(final Collection> a, final Collection> b)
传入两个Collection就可以了,我们常用的List或者Set,根据源码发现:
这个方法比较的是集合中的元素以及元素的个数,不管是List或者是Set,不要求顺序相同。
下面是一个例子,其中的源码可能因为版本更迭与最新的不同,但是原理是一样的:package collection;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.apache.commons.collections4.CollectionUtils;import org.junit.Test;public class Test1 {// CollectionUtils.isEqualCollection/** * isEqualCollection * * public static boolean isEqualCollection(Collection a, Collection b) Returns true iff the given Collections contain exactly the same elements with exactly the same cardinalities. * That is, iff the cardinality of e in a is equal to the cardinality of e in b, for each element e in a or b. * * Parameters: * a – the first collection, must not be null * b – the second collection, must not be null * Returns: * true iff the collections contain the same elements with the same cardinalities. * */@Testpublic void test1() {ArrayList arr1 = new ArrayList();arr1.add(“1”);arr1.add(“2”);arr1.add(“2”);arr1.add(“3”);arr1.add(“4”);arr1.add(“5”);ArrayList arr2 = new ArrayList();arr2.add(“1”);arr2.add(“1”);arr2.add(“2”);arr2.add(“3”);arr2.add(“5”);arr2.add(“4”);System.out.println(CollectionUtils.isEqualCollection(arr1, arr2));// copy的源码System.out.println(isEqualCollection(arr1, arr2));}public static boolean isEqualCollection(Collection a, Collection b) {if (a.size() != b.size())return false;Map mapa = getCardinalityMap(a);Map mapb = getCardinalityMap(b);if (mapa.size() != mapb.size())return false;for (Iterator it = mapa.keySet().iterator(); it.hasNext();) {Object obj = it.next();if (getFreq(obj, mapa) != getFreq(obj, mapb))return false;}return true;}private static Integer INTEGER_ONE = new Integer(1);public static Map getCardinalityMap(Collection coll) {Map count = new HashMap();for (Iterator it = coll.iterator(); it.hasNext();) {Object obj = it.next();Integer c = (Integer) count.get(obj);if (c == null)count.put(obj, INTEGER_ONE);elsecount.put(obj, new Integer(c.intValue() + 1));}return count;}private static final int getFreq(Object obj, Map freqMap) {Integer count = (Integer) freqMap.get(obj);if (count != null)return count.intValue();elsereturn 0;}}
本文网址:http://www.shaoqun.com/a/305405.html
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:admin@shaoqun.com。
0