Published 19 Sep, 2022

Java - Java Collections (LIFO Structure)

Category Java
Modified : Oct 03, 2022
86

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 Deque, but I am in Java 1.5.

I would like not to have to add another class to my structure but I am wondering if that is possible:

  1. Is there any class in the Collections framework (1.5) that does the job?

  2. If not, is there any way to turn a Queue in a LIFO Queue (aka Stack) without reimplementation?

  3. If not, which Interface or class should I extend for this task? I guess that keep the way that the guys of Sun have made with the Deque is a good start.

Thanks a lot.

EDIT: I forgot to say about the Stack class: I have my doubts about this class when I saw that it implements the Vector class, and the Vector class is a little bit obsolete, isn't it?

Answers

There are 4 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Java, Stack, Collections, Queue. These have been categorized in sections for a clear and precise explanation.

52

There's actually a Stack class: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Stack.html

If you don't want to use that, the LinkedList class (http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html) has addFirst and addLast and removeFirst and removeLast methods, making it perfect for use as a stack or queue class.


48

I realize I'm late to the party here, but java.util.Collections (Java 7) has a static 'asLifoQueue' that takes a Deque argument and returns (obviously) a LIFO queue view of the deque. I'm not sure what version this was added.

http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#asLifoQueue(java.util.Deque)


40

Stack class is slowly: methods are synchronized + Stack extends synchronized Vector


16

Deque & LinkedList

Just for the sake of completeness I'm providing an example using Deque interface and a LinkedList implementation.

    Deque<String> deque = new LinkedList<>();
    deque.add("first");
    deque.add("last");

    // returns "last" without removing it
    System.out.println(deque.peekLast());

    // removes and returns "last"
    System.out.println(deque.pollLast());

Backing up a Deque by a LinkedList is great for performance, since inserting and removing elements from it is done in constant time (O(1)).

Using a LinkedList alone:

    LinkedList<String> list = new LinkedList<>();
    list.add("first");
    list.add("last");

    // returns "last" without removing it
    System.out.println(list.getLast());

    // removes and returns "last"
    System.out.println(list.removeLast());