Why typical Array List implementations aren't double-ended?

前端 未结 4 1708
离开以前
离开以前 2020-12-11 18:47

Why aren\'t ArrayLists generally implemented to be double-ended, which would support fast amortized insertion in the front as well as the back?

Is there

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 19:17

    An ArrayList is simple; entries start at 0, and you can add stuff at the end (which might lengthen the array), but entry #X in the list is always backing_array[X].

    An ArrayDeque would be more complex; besides having to keep track of the start of the sequence (because it'd no longer be guaranteed to start at 0, unless you want O(N) shifts/unshifts), you'd also have to worry about the other end being "empty". That extra complexity comes at a cost; in the more common case (lists), the RTL would still have to do all the checks and index math necessary in a deque, slowing down the app for no real reason. Entry #X becomes backing_array[start+X], and bounds checks have extra math to them as well.

    So unless you have a real need for deque functionality, it's simpler and more efficient to stick with a list, at least when you're messing with arrays.

提交回复
热议问题