Advertisement
daniel_079

ArrayQueueModule

Dec 11th, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.08 KB | None | 0 0
  1. package queue;
  2.  
  3. public class ArrayQueueModule {
  4.     private static int head;
  5.     private static int tail;
  6.     private static int size;
  7.     private static Object[] queue = new Object[5];
  8.  
  9.     public static int size() {
  10.         return size;
  11.     }
  12.  
  13.     public static void enqueue(Object element) {
  14.         assert element != null;
  15.  
  16.         ensureCapacity(size + 1);
  17.         queue[tail] = element;
  18.         tail = (tail + 1) % queue.length;
  19.         size++;
  20.     }
  21.  
  22.     private static void ensureCapacity(int capacity) {
  23.         if (capacity < queue.length) {
  24.             return;
  25.         }
  26.  
  27.         Object[] newQueue = new Object[2 * capacity];
  28.         for (int i = 0; i < size; i++) {
  29.             newQueue[i] = queue[i];
  30.         }
  31.         queue = newQueue;
  32.     }
  33.    
  34.     public static Object element() {
  35.         assert size != 0;
  36.        
  37.         return queue[head];
  38.     }
  39.    
  40.     public Object dequeue() {
  41.         assert size != 0;
  42.        
  43.         Object x = queue[head];
  44.         head = (head + 1) % queue.length;
  45.         size--;
  46.         return x;
  47.     }
  48.    
  49.     public static boolean isEmpty() {
  50.         return size == 0;
  51.     }
  52.    
  53.     public static void clear() {
  54.         head = 0;
  55.         tail = 0;
  56.         size = 0;
  57.     }
  58.    
  59.    
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement