Iz E-študij, proste zakladnice študentskega znanja
//Vrsta s poljem
public class QueueArray implements Queue {
static final int DEFAULT_LENGTH = 100 ;
private Object elements[] ;
private int front, rear ;
public QueueArray() {
this(DEFAULT_LENGTH) ;
}
public QueueArray(int noElem) {
elements = new Object[noElem] ;
makenull() ;
}
public void makenull() {
front = 0 ;
rear = elements.length - 1 ;
}
public boolean empty() {
return incr(rear)==front ;
}
public Object front() throws Underflow {
if (empty()) // error
throw new Underflow() ;
return elements[front] ;
}
public void enqueue(Object x) throws Overflow {
if (incr(incr(rear))==front) //error: full queue
throw new Overflow() ;
else {
rear=incr(rear) ;
elements[rear] = x ;
}
}
public void dequeue() throws Underflow {
if (empty()) // error
throw new Underflow() ;
else front = incr(front) ;
}
private int incr(int pos) {
return (pos+1) % elements.length ;
}
public static void main(String[] args) {
QueueArray q = new QueueArray();
System.out.println("Testing class "+q.getClass() );
int i ;
try {
for (i = 1; i <= 5; i++) {
q.enqueue(new Integer(i));
System.out.println("Enqueing " + i);
}
while (!q.empty()) {
System.out.println("Dequeing " + q.front());
q.dequeue();
}
}
catch (Underflow e) {
System.out.println("Dequeing an empty queue in "+q.getClass());
}
catch (Overflow e) {
System.out.println("Queue is already full in "+q.getClass());
}
}
}