CollectionUtils.isEqualCollection(final Collection a, final Collection b)
CollectionUtils工具类中有一个查看两个Collection是否相等的方法。
public static boolean isEqualCollection(final Collection a, final Collection b) { if(a.size() != b.size()) { return false; } else { //获取以对象为键以对象的数量位置的Map Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); if(mapa.size() != mapb.size()) { return false; } else { Iterator it = mapa.keySet().iterator(); while(it.hasNext()) { Object obj = it.next(); //获取对象的数量,判断是否相等
if(getFreq(obj,mapa) != getFreq(obj,mapb)) { return false; } } return true; } } }
主要的方法是getCardinalityMap(Collection coll)方法,返回的结果是以对象为键,以对象的数量为值的Map。
public static Map getCardinalityMap(final 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); } else { count.put(obj,new Integer(c.intValue() + 1)); } } return count; }
从Map中获取对象数量的方法
private static final int getFreq(final Object obj, final Map freqMap) { Integer count = (Integer) freqMap.get(obj); if (count != null) { return count.intValue(); } return 0; }
注意:这里两个Collection中的对象需要实现hashcode()和equals()方法