SHARE
TWEET

generics stack

a guest Oct 13th, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class Stack<T> implements StackInterface<T> {
  2.  
  3.     private int size;
  4.     private int top = -1;
  5.  
  6.     private T[] stackArr;
  7.  
  8.     @SuppressWarnings("unchecked")
  9.     private Stack() {
  10.         size = 16;
  11.         stackArr = (T[]) new Object[size];
  12.     }
  13.  
  14.     @SuppressWarnings("unchecked")
  15.     private Stack(int curSize) {
  16.         size = curSize;
  17.         stackArr = (T[]) new Object[size];
  18.     }
  19.  
  20.     public void push(T entry) {
  21.         if (isFull()) {
  22.             System.out.println("Бля, щас как расширю");
  23.             ensureCapacity();
  24.         }
  25.         System.out.println("Adding: " + entry);
  26.         stackArr[++top] = entry;
  27.     }
  28.  
  29.     public T pop() throws Exception {
  30.         if (isEmpty()) {
  31.             throw new Exception("Бля, ну ты и долбоёб");
  32.         }
  33.         T entry = stackArr[top--];
  34.         System.out.println("Removed entry: " + entry);
  35.         return entry;
  36.     }
  37.  
  38.     public T peek() {
  39.         return stackArr[top];
  40.     }
  41.  
  42.     @SuppressWarnings("unchecked")
  43.     private void ensureCapacity() {
  44.         T[] newStack = (T[]) new Object[2 * size];
  45.         if (size >= 0) {
  46.             System.arraycopy(stackArr, 0, newStack, 0, size);
  47.         }
  48.         size *= 2;
  49.         stackArr = newStack;
  50.     }
  51.  
  52.     public boolean isEmpty() {
  53.         return (top == -1);
  54.     }
  55.  
  56.     public boolean isFull() {
  57.         return (top == size - 1);
  58.     }
  59.  
  60.     public int size() {
  61.         return size;
  62.     }
  63.  
  64.     public static void main(String[] args)  {
  65.         Stack<Object> integerStack = new Stack<>(4);
  66.         for (int i = 1; i <= 17; i++) {
  67.             integerStack.push(i);
  68.         }
  69.         System.out.println(integerStack.size());
  70.     }
  71. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top