從學Java開始, 就一直大腦記着 arrayList 底層是數組 ,查詢快, 插入慢, 有移動的動作。linkedList 底層鏈表, 插入快 查詢慢,今天寫了例子跑了跑, 果然。
public class ListTest { public static void main(String[] args)throws Exception { Thread thread = new Thread(()->{ addArraylist(); }); Thread thread2 = new Thread(()->{ addLinkedList(); }); thread.start(); thread.join(); thread2.start(); thread2.join(); } private static void addArraylist(){ ArrayList<String > arrayList = new ArrayList(); long begin2 = System.currentTimeMillis(); for(int j= 0 ;j<1000000;j++){ arrayList.add(j+"==="); } System.out.println("arraylist花費了:"+(System.currentTimeMillis()-begin2)+"毫秒"); System.out.println(arrayList.size()); } private static void addLinkedList(){ LinkedList <String >linkedList = new LinkedList(); long begin = System.currentTimeMillis(); for( int i=0 ;i<1000000;i++){ linkedList.add(i+"==="); } System.out.println("linkedList花費了:"+(System.currentTimeMillis()-begin)+"毫秒"); System.out.println(linkedList.size()); } }
=============輸出結構是:
數據量比較少時 ,看的不明顯, 當數據在100000以內 ,結果差不多, 大於100 萬, 感覺到執行時間差距很大了。心里有個底。
==================================================================================
說下兩種集合的用途:
數組, 開發中主要是為了查詢快,這個用的最多, 比如從數據庫分頁查詢 數據, 需要 遍歷 。
鏈表 Linkedlist 用作 堆棧(比如虛擬機棧 , 大量的變量作用,指令操作, 基本都鏈表結構), 隊列 比較多, 比如 線程池的 隊列啊, 插入刪除快。
====================================================================================
從 JVM堆內存分析 效率為啥差別這么大。
為啥數組插入慢,數組有個默認大小,比如16 ,數組在初始化的時候在 內存中會被分配一塊連續的內存,第一個元素進來。問角標 0 ,你存東西了嗎, 沒有, 我就進去啦。后面的元素在插入的時候,要詢問多次,【比如第一萬個元素, 要詢問9999次, 你這位置有人不?】 時間復雜度為O(n),數組的大小;
而 鏈表不是這樣, 並不是一段連續的內存,第一個元素進來, 記下自己的 【value =“張三” ,PRE =null(元素的 hash值) ,NEXT = null】,
第二個元素進來, 拿到上一個元素的值,先把張三的 next 改成自己 ,【value =“張三” ,PRE =null(元素的 hash值) ,NEXT = 5654654654(“李四的地址值”)】
然后把自己加進去了,類似於【value=“李四,PRE=343434("張三”),next=null】。
插入的時間復雜度為O(1),就很快了。 不用移動指針, 就特別 爽。