arraylist vs linked list .why linked list is slower when we add in the end?

╄→尐↘猪︶ㄣ 提交于 2019-12-11 05:39:40

问题


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


public class CompareList {
public static void main(String[] args) {
    List<Integer> ArrayList = new ArrayList<Integer>();
    List<Integer> LinkedList = new LinkedList<Integer>();
    doCalculations("ArrayList",ArrayList);
    doCalculations("LinkedList",LinkedList);    
}
private static void doCalculations(String type,List<Integer> List){
    for(int i=0;i<1E5;i++){
        List.add(i);    
    }
    Long start = System.currentTimeMillis();
    /*
     To add elements in the end 
    for(int i=0;i<1E5;i++){
        List.add(i);    
    }
    */
    for(int i=0;i<1E5;i++){
        List.add(0,i);
    }
    Long end = System.currentTimeMillis();
    System.out.println("time taken" +" "+ (end-start) + "ms for" +" "+ type);
}
}

time taken 13ms for ArrayList time taken 64ms for LinkedList

i know this is duplicate question ,but please don't remove this ,whatever answers they gave to this question i was unable understand ,Can anyone explain this in simple words why this linked list is slower when we add element in the end?


回答1:


What you're currently doing here is a micro benchmark. This is not an easy task, because you have to take into account all these tips: How do I write a correct micro-benchmark in Java?.

Still, there's no need to reinvent the wheel. There are frameworks that ease this work like JUnitBenchmarks and Caliper that help you to perform real benchmarks for your pieces of code/algorithms by using JUnit tests.




回答2:


linked list is slower cuz it is like a train.......it have to check each element and check it is value ..until it find the matched element..so think of it like chained train and you want to go from the first of the train to the end



来源:https://stackoverflow.com/questions/23685054/arraylist-vs-linked-list-why-linked-list-is-slower-when-we-add-in-the-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!