Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collections (LIFO Structure)

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?

like image 383
David Santamaria Avatar asked Nov 19 '08 16:11

David Santamaria


People also ask

Is there a class for LIFO in Java?

The Stack class has been supplanted by more modern classes, as explained in the Javadoc: A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class.

How is LIFO implemented in Java?

A Stack is a Last In First Out (LIFO) data structure. It supports two basic operations called push and pop. The push operation adds an element at the top of the stack, and the pop operation removes an element from the top of the stack. The Stack class extends Vector which implements the List interface.

Which data structure uses LIFO?

The data structure that implements LIFO is Stack.

What is LIFO structure?

LIFO is an abbreviation for last in, first out. It is a method for handling data structures where the first element is processed last and the last element is processed first.


2 Answers

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.

like image 87
Eli Courtwright Avatar answered Sep 23 '22 20:09

Eli Courtwright


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)

like image 39
JVMATL Avatar answered Sep 19 '22 20:09

JVMATL