数据结构 -- 用ArrayList和LinkedList分析一个小问题(Integer集合中删除偶数)的性能

问题

  • 删除一个Integer集合中所有的偶数,采用ArrayList还是LinkedList,并给出分析代码

代码1

public static void removeEventVer1(List<Integer> lst){
    int i = 0;
    while(i < lst.size()){
        if(lst.get(i)%2==0){
            lst.remove(i);
        }else{
            i++
        }
    }
}
  • 首先对于ArrayList来说,需要从头遍历一次集合,在执行remove方法的时候,被remove元素后面的元素依次前进一位。所采用的时间就是二次时间。不是线性时间
  • 对于LinkedList,同样需要遍历整个集合,在执行get方法时,每次都要表头开始查找,因此也是二次时间

代码2

  • 采用增强for循环,但是这个对于使用集合的remove因此会报出异常。(注意:增强for循环中不能用集合remove,因为底层的迭代器认为这是非法的)
public static void removeEventVer2(List<Integer> lst){
    for(Integer x:lst){
        if(x%2==0){
            lst.remove(x);
        }
    }
}

代码3

public static void removeEventVer3(List<Integer> lst){
    Iterator<Integer> itr = lst.iterator();
    while(itr.hasNext()){
        if(itr.next()%2==0){
            itr.remove();
        }
    }
}
  • 对于ArrayList来说依然是二次时间,但是对于LinkedList来说确实线性时间,因为在一次遍历就能删除完这些偶数。用迭代器的remove是可以的。不能用集合的remove。
发布了134 篇原创文章 · 获赞 91 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/weixin_44588495/article/details/102597213