A post on LinkedList says:
LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.
I’m not understanding what will qualify for grabbing the element in the middle?
In below piece of code, assuming arrL is a LinkedList that holds 50 elemnets, when counter j reaches 20, and program executes arrL.get(20).. Does that mean program is grabbing the element in middle? Also in below program I’m just walking the list forward, isn’t?
for(int j=0;j<arrL.size();++j){
arrL.get(j);
}
Yes, in each iteration you are traversing the list from the beginning to the j-th element, so the overall loop performance is
n^2(very poor). That’s because in each iteration you have independentget()call which has linear performance.If you use iterator on the other hand, you will be traversing the list one element at a time, going forward by one element in each iteration, which is much faster:
or better:
BTW this is a very basic data-structure question, Java has nothing to do here…