Package generic.util

Class DequePush<E>

  • Type Parameters:
    E - the type of element pushed to the stack
    All Implemented Interfaces:
    java.lang.AutoCloseable

    public class DequePush<E>
    extends java.lang.Object
    implements java.lang.AutoCloseable
    A context utility allowing stack management via a try-with-resources block
    • Field Summary

      Fields 
      Modifier and Type Field Description
      protected java.util.Deque<E> stack  
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected DequePush​(java.util.Deque<E> stack, E elem)  
    • Method Summary

      All Methods Static Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void close()  
      static <E> DequePush<E> push​(java.util.Deque<E> stack, E elem)
      Push an element to the given stack
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • stack

        protected java.util.Deque<E> stack
    • Constructor Detail

      • DequePush

        protected DequePush​(java.util.Deque<E> stack,
                            E elem)
    • Method Detail

      • close

        public void close()
        Specified by:
        close in interface java.lang.AutoCloseable
      • push

        public static <E> DequePush<E> push​(java.util.Deque<E> stack,
                                            E elem)
        Push an element to the given stack
        Parameters:
        stack - the stack
        elem - the element
        Returns:
        a context used to pop the element This is an idiomatic convenience, as in a try-with-resources block:
         
         Deque<String> stack = new LinkedList<>();
         try(DequePush<?> p = DequePush.push(stack, "Hello, World!\n")) {
             System.out.println(stack.peek());
         }
         
         
        This idiom can be very useful if there is complex logic between the push and pop. It's easy to forget to pop; however, this convenience comes at the cost of a heap allocation.