001: import java.util.*; 002: 003: /** 004: A first-in, first-out bounded collection of objects. 005: */ 006: public class Queue extends AbstractCollection 007: { 008: /** 009: Constructs an empty queue. 010: @param capacity the maximum capacity of the queue 011: @precondition capacity > 0 012: */ 013: public Queue(int capacity) 014: { 015: elements = new Object[capacity]; 016: count = 0; 017: head = 0; 018: tail = 0; 019: } 020: 021: public Iterator iterator() 022: { 023: return new 024: Iterator() 025: { 026: public boolean hasNext() 027: { 028: return visited < count; 029: } 030: 031: public Object next() 032: { 033: int index = (head + visited) % elements.length; 034: Object r = elements[index]; 035: visited++; 036: return r; 037: } 038: 039: public void remove() 040: { 041: throw new UnsupportedOperationException(); 042: } 043: 044: private int visited = 0; 045: }; 046: } 047: 048: /** 049: Remove object at head. 050: @return the object that has been removed from the queue 051: @precondition size() > 0 052: */ 053: public Object removeFirst() 054: { 055: Object r = elements[head]; 056: head = (head + 1) % elements.length; 057: count--; 058: return r; 059: } 060: 061: /** 062: Append an object at tail. 063: @param anObject the object to be appended 064: @return true since this operation modifies the queue. 065: (This is a requirement of the collections framework.) 066: @precondition !isFull() 067: */ 068: public boolean add(Object anObject) 069: { 070: elements[tail] = anObject; 071: tail = (tail + 1) % elements.length; 072: count++; 073: return true; 074: } 075: 076: public int size() 077: { 078: return count; 079: } 080: 081: /** 082: Checks whether this queue is full. 083: @return true if the queue is full 084: */ 085: public boolean isFull() 086: { 087: return count == elements.length; 088: } 089: 090: /** 091: Gets object at head. 092: @return the object that is at the head of the queue 093: @precondition size() > 0 094: */ 095: public Object getFirst() 096: { 097: return elements[head]; 098: } 099: 100: private Object[] elements; 101: private int head; 102: private int tail; 103: private int count; 104: }