ArrayList Vs LinkedList

前端 未结 9 645
一整个雨季
一整个雨季 2020-11-27 10:53

I was following a previous post on this that says:

For LinkedList

  • get is O(n)
  • add is O(1)
  • remove is O(n)
相关标签:
9条回答
  • 2020-11-27 11:20

    O notation analysis provides important information, but it has it's limitations. By definition O notation analysis considers that every operation takes approximately the same time to execute, which is not true. As @seand pointed out, linked lists internally uses more complex logic to insert and fetch elements (take a look at the source code, you can ctrl+click in your IDE). ArrayList internally only needs to insert elements into an array and increase its size once in a while (which even being an o(n) operation, in practice can be accomplished pretty fast).

    Cheers

    0 讨论(0)
  • 2020-11-27 11:28

    The big-O-notation is not about absolut timings, but about relative timings, and you can't compare the numbers of one algorithm to another.

    You only get information how the same algorithm reacts to increasing or decreasing numbers of tuples.

    One algorithm might take an hour for one operation, and 2h for two operations, and is O(n), and another one is O(n) too, and takes one millisecond for one operation, and two milliseconds for two operations.

    Another issue if measuring with the JVM is the optimization of the hotspot-compiler. A do-nothing-loop might be eliminated by the JIT-compiler.

    A third thing to consider is the OS and JVM, using caches and running the garbage collection meanwhile.

    0 讨论(0)
  • 2020-11-27 11:31

    It's hard to find a good use case for LinkedList. If you only need to make use of the Dequeu interface, you should probably use ArrayDeque. If you really need to use the List interface, you will often hear the suggestion to use always ArrayList because LinkedList behaves really poorly in accessing a random element.

    Unfortunately also ArrayList has its performance problems if elements at the beginning or in the middle of the list must be removed or inserted.

    There is however a new list implementation called GapList which combines the strengths of both ArrayList and LinkedList. It has been designed as drop-in replacement for both ArrayList and LinkedList and therefore implements both the interfaces List and Deque. Also all public methods provided by ArrayList are implemented (ensureCapacty, trimToSize).

    GapList's implementation guarantees efficient random access to elements by index (as ArrayList does) and at the same time efficient adding and removing elements to and from head and tail of the list (as LinkedList does).

    You find more information about GapList at http://java.dzone.com/articles/gaplist-%E2%80%93-lightning-fast-list.

    0 讨论(0)
提交回复
热议问题