org.apache.commons.collections工具类使用时需要避免的坑,A集合B集合的交集C,A与C的补集、并集、集合是否相等,B集合包含A集合?

CollectionUtils.intersection漏洞: 其中一个集合为空的情况,空指针异常需要用户进行判断后使用;

求交集

CollectionUtils.intersection(A,B); 需要判断A、B集合是否为空!!!

求并集

java.util.List方法boolean addAll(Collection<? extends E> c);需要用户自己保证添加的集合不为空

A集合B集合的交集C,A与C的补集

/** 
* 求两个集合中,collection中去掉交集后的数据 
* @param collection 
* @param remove 
* @return 
*/ 
private List<Long> removeAllIntersection(List<Long> collection, List<Long> remove) { 
    if (CollectionUtils.isEmpty(remove)) { 
        return collection; 
    } 
    List list = new ArrayList(); 
    if (CollectionUtils.isEmpty(collection)) { 
        return list; 
    } 
    Iterator iter = collection.iterator(); 
    while (iter.hasNext()) { 
        Object next = iter.next(); 
        if (!remove.contains(next)) { 
            list.add(next); 
        } 
    } 
    return list; 
}

判断两个集合是否相等

/** 
* 比较source1、source2 是否相等 
* 
* @param source1 
* @param source2 
* @return 
*/ 
private boolean compareList(List<Long> source1, List<Long> source2) { 
    if (CollectionUtils.isEmpty(source1) && CollectionUtils.isNotEmpty(source2)) return false; 
    if (CollectionUtils.isNotEmpty(source1) && CollectionUtils.isEmpty(source2)) return false; 
    if (CollectionUtils.isEmpty(source1) && CollectionUtils.isEmpty(source2)) return true; 
                        
    return source1.containsAll(source2) && source2.containsAll(source1); 
}

判断A集合是否包含于B集合

private boolean checkCollectionOneContainsOther(List<Long> one, List<Long> other) { 
    if (CollectionUtils.isEmpty(one) && CollectionUtils.isEmpty(other)) { 
        return true; 
    } 
    if (CollectionUtils.isEmpty(one) && CollectionUtils.isNotEmpty(other)) { 
        return true; 
    } 
    if (CollectionUtils.isNotEmpty(one) && CollectionUtils.isEmpty(other)) { 
        return false; 
    } 
    return other.containsAll(one); 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值