欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 中Collection 比较

程序员文章站 2022-07-15 09:06:09
...
   public class ListTest {
    private static Random random = new Random();
    public static void main(String[] args){
        ArrayList<String> arraylist = new ArrayList();
        LinkedList<String> linkedlist = new LinkedList();
        HashMap<String,Object> map = new HashMap();
        HashSet<String> set = new HashSet();
        for(int i=0;i<50000;i++){
            String r = randomString();
            arraylist.add(r);
            linkedlist.add(r);
            map.put(r, r);
            set.add(r);
        }
       
        System.out.println("arraylist size "+arraylist.size());
        System.out.println("linkedlist size "+linkedlist.size());
        System.out.println("map size "+map.size());
        System.out.println("set size "+set.size());
       
       
        System.out.println("------");
        long begin = System.currentTimeMillis();
        for(int j=0;j<arraylist.size();j++){
            arraylist.contains(arraylist.get(j));
        }
        System.out.println("arraylist time "+(System.currentTimeMillis()-begin));
       
       
        begin = System.currentTimeMillis();
        for(int j=0;j<arraylist.size();j++){
            linkedlist.contains(arraylist.get(j));
        }
        System.out.println("linkedlist time "+(System.currentTimeMillis()-begin));
       
        begin = System.currentTimeMillis();
        for(int i=0;i<100;i++){
            for(int j=0;j<arraylist.size();j++){
                map.containsKey(arraylist.get(j));
            }
        }
        System.out.println("map time "+(System.currentTimeMillis()-begin));
       
        begin = System.currentTimeMillis();
        for(int i=0;i<100;i++){
            for(int j=0;j<arraylist.size();j++){
                set.contains(arraylist.get(j));
            }
        }
        System.out.println("set time "+(System.currentTimeMillis()-begin));
       
    }
    protected static String randomString() {
        return Long.toString(random.nextLong(), 36);
    }
}
在我的机器上,结果如下:
arraylist size 50000
linkedlist size 50000
map size 50000
set size 50000
------
arraylist time 49328
linkedlist time 57641
map time 625
set time 578


可见呀,如果是在集合中查询某个对象是否存在,是HashSet的速度最快,而且比List快将近1万倍。
相关标签: java集合测试