Java Collections (LIFO Structure)

前端 未结 6 1468
栀梦
栀梦 2020-12-05 06:55

I am looking in the Collections framework of Java for a LIFO Structure (Stack) without any success. Basically I want a really simple stack; my perfect option would be a Dequ

6条回答
  •  再見小時候
    2020-12-05 07:16

    Deque, ArrayDeque, & LinkedList

    While this was asked a while ago it might be wise to provide a JDK6+ answer which now provides a Deque (deck) interface which is implemented by the ArrayDeque data structure and the LinkedList was updated to implement this interface.

    ConcurrentLinkedDeque & LinkedBlockingDeque

    Specialised forms for concurrent access also exist and are implemented by ConcurrentLinkedDeque and LinkedBlockingDeque.

    LIFO versus FIFO

    The one thing that is great about a deque is that it provides both LIFO (stack) and FIFO (queue) support it can cause confusion as to which methods are for queue operations and which are for stack operations for newcomers.

    IMHO the JDK should have a Stack interface and a Queue interface that could still be implemented by the likes of ArrayDeque but only expose the subset of methods required for that structure, i.e. a LIFO could define pop(), push() and peek(), then in the context of

    LIFO stack = new ArrayDeque<>();
    

    only stack operations are exposed which stops someone accidentally calling add(E) when push(E) was intended.

提交回复
热议问题