Java 集合中的方法性能分析


前言

      暂无
      
      
      
      

一、List集合

1.1、Collection 中 get() 和 remove()方法的效率

示例一

    public static int sum(List<Integer> ls){
    
    
        int total=0;
        for(int i=0;i<ls.size();i++){
    
    
            total+=ls.get(i);
        }
        return total;
    }

      上面这个求一个 List 的所有元素和的代码,在 ArrayList 中的时间复杂度为 O(n),在 LInkedList 中的时间复杂度为 O(n2)。

      区别在于 get() 方法,它在 ArrayList 中的为常数时间,在 LInkedList 中为线性时间。当然 remove() 方法也是一样的。但是采用迭代器来实现的话,上面代码的运行时间不管是 ArrayList 还是 LInkedList ,都是线性时间 O(n)。

      contains() 方法没有区别,这二者均为线性时间。

示例二

      删除一个表中的所有偶数元素。
.
      可能的想法是:创建一个新的只包含旧表中奇数元素的表,删除旧表中元素,再将新表拷贝过去即可。

      如果不采用这种创建新表的话,比如采用 remove() 方法的话,见代码1:

    public static void removeEvens(List<Integer> ls){
    
    
        int i=0;
        while(i<ls.size()){
    
    
            if(ls.get(i)%2==0)
                ls.remove(i);
            else
                ++i;
        }
    }

      代码1在 ArrayList 上由于 remove() 的原因(数组移动花费线性时间),它花费二次时间。而 LinkedLIst 由于 get() 和 remove() 的原因(元素搜索花费线性时间),所以它也花费二次时间。

      采用迭代器来实现,见代码2

    public static void removeEvens(List<Integer> ls){
    
    
        Iterator it=ls.iterator();
        while(it.hasNext()){
    
    
            int tmp=(int)it.next();
            if(tmp%2==0)
                it.remove();
        }
    }

      用迭代器的话有什么不同呢?对于 ArrayList 而言,迭代器的 remove() 仍然花费线性时间,因为数组需要移动,而整个程序仍然花费二次时间;但是对于 LInkedList 而言,迭代器的 remove() 花费常数时间,因为该迭代器总是位于需要被删除的节点(或者在其附近),所以整个程序仅花费线性时间,而不是二次时间。


总结

      未完~

猜你喜欢

转载自blog.csdn.net/Little_ant_/article/details/121598989