• Java学习笔记(1)----规则集和线性表性能比较


      为了比较 HashSet,LinkedHashSet,TreeSet,ArrayList,LinkedList 的性能,使用如下代码来测试它们加入并删除500000个数据的时间:

    package src;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.LinkedList;
    import java.util.TreeSet;
    
    
    
    
    public class Solution {
    
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Collection<Integer>set1=new HashSet<Integer>();
            System.out.println("Time for hash set is "+getTestTime(set1,500000)+" milliseconds");
            
            Collection<Integer>set2=new LinkedHashSet<Integer>();
            System.out.println("Time for linked hash set is "+getTestTime(set2, 500000)+" milliseconds");
            
            Collection<Integer>set3=new TreeSet<Integer>();
            System.out.println("Time for tree set is "+getTestTime(set3, 500000)+" milliseconds");
            
            Collection<Integer>set4=new ArrayList<Integer>();
            System.out.println("Time for arraylist is "+getTestTime(set4, 500000)+" milliseconds");
            
            Collection<Integer>set5=new LinkedList<Integer>();
            System.out.println("Time for linked list is "+getTestTime(set5, 500000)+" milliseconds");
            
            System.out.println("
    Game Over!");
        }
        
        public static long getTestTime(Collection<Integer>c,int size){
            long startTime=System.currentTimeMillis();
            List<Integer>list=new ArrayList<Integer>();
            for(int i=0;i<size;i++){
                list.add(i);
            }
            
            Collections.shuffle(list);
            for(int ele:list){
                c.add(ele);
            }
            
            Collections.shuffle(list);
            
            for(int ele:list){
                c.remove(ele);
            }
            
            long endTime=System.currentTimeMillis();
            return endTime-startTime;
        }
    }

    运行结果如下:

    Time for hash set is 372 milliseconds
    Time for linked hash set is 404 milliseconds
    Time for tree set is 936 milliseconds
    Time for arraylist is 200759 milliseconds
    Time for linked list is 473436 milliseconds
    
    Game Over!

    可以看到,速度由快到慢依次是:HashSet,LinkedHashSet,TreeSet,ArrayList,LinkedList。

  • 相关阅读:
    Excel2010表格里设置每页打印时都有表头
    新手常见Python运行时错误
    如何查看某个端口被谁占用
    ubuntu更换阿里源
    c# 值类型与引用类型(转)
    vs2015 企业版 专业版 密钥
    csdn中使用Git的一些注意问题
    在notepad++中快速插入当前时间方法
    EF6 code first 新建项目注意问题
    vs2015新建web应用程序空模板和添加webapi的模板生成文件的比较
  • 原文地址:https://www.cnblogs.com/dongling/p/5741709.html
Copyright © 2020-2023  润新知