Why no tail() or head() method in List to get last or first element?

前端 未结 8 862
死守一世寂寞
死守一世寂寞 2020-12-29 04:45

I recently had a discussion with a collegue why the List interface in Java doesn\'t have a head() and tail() method.

In order to implement

相关标签:
8条回答
  • 2020-12-29 05:33

    head() is provided via list.iterator().next(), list.get(0), etc.

    It is only reasonable to provide tail() if the list is doubly linked with a tail pointer, or based on an array, etc., Neither of these aspects is specified for the List interface itself. Otherwise it could have O(N) performance.

    0 讨论(0)
  • 2020-12-29 05:34

    peekLast method is already defined in Deque interface.
    Moreover, It's obligatory for deque to have such a functionality. So, there's no point to define it in List or any other interface.
    It's just convenient to split the functionality. If you need random access then you should implement List. If you need to access the tail efficiently then you should implement Deque. You can easily implement both of them (LinkedList does this, actually).

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