关于执行效率采坑List.removeAll

今天开发被removeALL坑了
一、HashSet.contains()的效率高于List.contains()
List调用contains方法时,每次都会重新遍历集合中的所有元素,并调用equals()方法,时间复杂度为O(n)。

HashSet调用contains方法时,会直接根据对象的Hash值定位集合中的元素,然后调用equals()方法,时间复杂度为O(1) 。

二、LinkedList.remove()效率高于ArrayList.remove()
ArrayList的实现是基于动态数组,每删除一个元素,其后面的元素都要往前移动,这种方式效率低,消耗资源大。

LinkedList的实现是基于双向链表,删除元素只需要改变前后节点的位置信息。

三、LinkedList.iterator()效率高于LinkedList.for()
使用Iterator迭代器时不用考虑集合下标的问题,也不用担心ConcurrentModificationException异常

ArrayList 对随机访问比较快,而for循环中的get(),采用的即是随机访问的方法,因此在 ArrayList 里,for循环较快
LinkedList 则是顺序访问比较快,Iterator 中的 next(),采用的即是顺序访问的方法,因此在 LinkedList 里,使用 Iterator 较快。

作者:风静花犹落
链接:https://www.jianshu.com/p/4ec2d1194443
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

/**
 * 差集
 */
public static List<String> differenceList(List<String> maxList, List<String> minList) {
    // 大集合用LinkedList
    LinkedList<String> linkedList = new LinkedList<>(maxList);
    // 小集合用HashSet
    HashSet<String> hashSet = new HashSet<>(minList);
    // 采用Iterator迭代器进行遍历
    Iterator<String> iterator = linkedList.iterator();

    while (iterator.hasNext()) {
        if (hashSet.contains(iterator.next())) {
            iterator.remove();
        }
    }
    return new ArrayList<>(linkedList);
}

/**
 * 交集
 */
public static List<String> intersectList(List<String> maxList, List<String> minList) {
    // 大集合用LinkedList
    LinkedList<String> linkedList = new LinkedList<>(maxList);
    // 小集合用HashSet
    HashSet<String> hashSet = new HashSet<>(minList);
    // 采用Iterator迭代器进行遍历
    Iterator<String> iterator = linkedList.iterator();

    while (iterator.hasNext()) {
        if (!hashSet.contains(iterator.next())) {
            iterator.remove();
        }
    }
    return new ArrayList<>(linkedList);
}

/**
 * 并集
 */
public static List<String> unionList(List<String> maxList, List<String> minList) {
    Set<String> treeSet = new TreeSet<>(maxList);
    // Set自动去重
    treeSet.addAll(minList);
    return new ArrayList<>(treeSet);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值