001package horstmann.ch09_queue1; 002import java.util.ArrayList; 003/** 004 A first-in, first-out bounded collection of objects. 005 */ 006public class BoundedQueue<E> 007{ 008 /** 009 Constructs an empty queue. 010 @param capacity the maximum capacity of the queue 011 */ 012 public BoundedQueue(int capacity) 013 { 014 elements = new ArrayList<E>(capacity); 015 head = 0; 016 tail = 0; 017 size = 0; 018 } 019 020 /** 021 Removes the object at the head. 022 @return the object that has been removed from the queue 023 <p><b>Precondition:</b> !isEmpty()</p> 024 */ 025 public E remove() 026 { 027 if (debug) System.out.print("removeFirst"); 028 E r = elements.get(head); 029 if (debug) System.out.print("."); 030 head++; 031 if (debug) System.out.print("."); 032 size--; 033 if (head == elements.size()) 034 { 035 if (debug) System.out.print("."); 036 head = 0; 037 } 038 if (debug) 039 System.out.println("head=" + head + ",tail=" + tail 040 + ",size=" + size); 041 return r; 042 } 043 044 /** 045 Appends an object at the tail. 046 @param newValue the object to be appended 047 <p><b>Precondition:</b> !isFull();</p> 048 */ 049 public void add(E newValue) 050 { 051 if (debug) System.out.print("add"); 052 elements.set(tail,newValue); 053 if (debug) System.out.print("."); 054 tail++; 055 if (debug) System.out.print("."); 056 size++; 057 if (tail == elements.size()) 058 { 059 if (debug) System.out.print("."); 060 tail = 0; 061 } 062 if (debug) 063 System.out.println("head=" + head + ",tail=" + tail 064 + ",size=" + size); 065 } 066 067 public boolean isFull() 068 { 069 return size == elements.size(); 070 } 071 072 public boolean isEmpty() 073 { 074 return size == 0; 075 } 076 077 public void setDebug(boolean newValue) 078 { 079 debug = newValue; 080 } 081 082 private ArrayList<E> elements; 083 private int head; 084 private int tail; 085 private int size; 086 private boolean debug; 087}