How to create a stack in Java without using the standard Stack class?
  • 2
    See the question (right next) about creating your list in java. In fact, it is very similar. - avp
  • 2
    There are also such "waves" of questions =) can this be done in schools homework on computer science on Monday?)) - Gorets
  • @Gorets, a regular university assignment. I think many did the same thing in the first year. - angry

2 answers 2

In general, it is not clear what does not suit the standard class. If very necessary, then

  1. either take another package
  2. or implement independently.

For example, get into the source , view the implementation and rewrite it for yourself. Example:

import java.util.ArrayList; public class CustomStack<T> extends ArrayList<T> { public void push(T o) { add(o); } public T pop() { return remove(size() - 1); } } 
  • @ Hi, very interesting answer (link source). I looked and realized that the possible implementation efficiency (collections of objects based on an array (there really is a lot of copying to a new object)) can only be caused by a non-trivial implementation of public static native void arraycopy () (defined in docjar.com/html/api/java/lang /System.java.html ). Do you happen to have links to native sources? Very interesting. - avp pm
  • IMHO so it would be better: public class CustomStack <T> {private ArrayList <T> = new ArrayList <T> (); public void push (T o) {l.add (o); } public T pop () {return l.remove (l.size () - 1); }} - jmu
  • @jmu what?) so that you use the ArrayList for other purposes? By the way, I missed l - Gorets
  • And why not do it through LinkedList and not compare it on different modes with both the standard implementation (through Vector) and the one offered on ArrayList (in fact Vector, but without syncronized methods)? If, in fact, the usual university assignment (comment @Angry Bird), it would have turned out a good study. And the student plus and the HashCode community (if the results publish) benefit. - avp
  • 2Gorets first is not me. secondly, “not to its intended purpose” is still in doubt, - if you leave the methods of the sheet then the stack will cease to be a stack. although of course it would be better if the linked list would use ps missing a letter without IDE is not an error :) - jmu

Using Collections.asLifoQueue you can make a stack from Deque (to be exact, a Queue with LIFO logic equivalent to a stack):

 Queue<String> stack = Collections.asLifoQueue(new ArrayDeque<>()); 

In the resulting object, all Queue methods will work correctly for the stack.

 stack.addAll(Arrays.asList("a", "b", "c", "d", "e")); //e System.out.println(stack.peek()); //edcba stack.forEach(element -> System.out.print(element)); 

Actually, this is the most acceptable way to create a stack using the JDK classes. The Stack class is not recommended (see Stack Class in Java )