Package generic.util

Class DequePush<E>

java.lang.Object
generic.util.DequePush<E>
Type Parameters:
E - the type of element pushed to the stack
All Implemented Interfaces:
AutoCloseable

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

    • stack

      protected Deque<E> stack
  • Constructor Details

    • DequePush

      protected DequePush(Deque<E> stack, E elem)
  • Method Details

    • close

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

      public static <E> DequePush<E> push(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.