0

I know Java screw up stack implementation - by extending Vector. Vector is synchronized by default. Reading the java doc, and it says that to create a stack,

 Deque<Integer> stack = new ArrayDeque<Integer>();

Since I am relative new to java. My question is: is this the best practice to define stack in Java?

2
  • thanks @pczeus. Not exact the duplication per say, just want to confirm my understanding of java practice. Commented Mar 6, 2016 at 2:12
  • I think ArrayDeque is your best bet. Commented Mar 6, 2016 at 2:30

2 Answers 2

1

Read the javadoc of Stack:

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. For example:

Deque<Integer> stack = new ArrayDeque<Integer>();

Even the javadoc of Deque says it:

Deques can also be used as LIFO (Last-In-First-Out) stacks. This interface should be used in preference to the legacy Stack class.

Is it "best practice" to follow the suggestions of the java documentation?
Yeah.

Sign up to request clarification or add additional context in comments.

Comments

0

in general(not being language specific), if you want dynamic stack implementation, Linked List-based implementation provides a good and efficient stack implementation. If you don't want a dynamic implementation, using arrays would also be a very good implementation. In java Deque gives a great performance. OR if you want and alternative, you can also try this example which uses inbuilt Stack :

    static void showpush(Stack st, int a) {
      st.push(new Integer(a));
    //add appropriate print statements
   }

   static void showpop(Stack st) {
      Integer a = (Integer) st.pop();
    //add appropriate print statements
   }

   public static void main(String args[]) {
      Stack st = new Stack();
      showpush(st, 42);
      showpush(st, 66);
      showpush(st, 99);
      showpop(st);
      showpop(st);
      showpop(st);
   }

1 Comment

I know it is an example. two nitty picks: 1. Stack<T> might be better. 2. We do not need to do auto boxing again for new Integer(a). Also Stack implementation is awful bad from performance’s perspective. See my original question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.