/**
* Classe ArrayQueue:
*
* Realizzazione del
TDA Coda mediante array circolare.
*/
public class ArrayQueue
implements
Queue
{
static
final int DEFAULT_SIZE
= 32 ;
protected
Object
[ ] theArray;
protected
int
size, front, back ;
/**
*
Costruttore della coda.
*/
public
ArrayQueue
(
) {
theArray = new Object[
DEFAULT_SIZE ] ;
size = 0 ;
front = 0 ;
back = -1 ;
}
/**
*
Verifica che la coda sia logicamente vuota.
*
@return <code>true</code> se la coda è vuota;
*
<code>false</code> altrimenti.
*/
public
boolean
isEmpty
(
) {
return size == 0 ;
}
/**
*
Svuota la coda.
*/
public
void
clear
( ) {
size = 0 ;
front = 0 ;
back = -1 ;
}
/**
*
Restituisce l'oggetto in testa alla coda senza estrarlo.
*
@return l'oggetto in testa.
*
@exception EmptyQueueException con coda vuota.
*/
public
Object
front
(
) {
if ( isEmpty
( ) )
throw new EmptyQueueException
( ) ;
return theArray[ front ] ;
}
/**
*
Inserisce un oggetto in fondo alla coda.
*
@param x l'oggetto da inserire.
*
@return l'oggetto inserito.
*
@exception IllegalArgumentException se l'argomento passato
*
è <code>null</code>.
*/
public
Object
enqueue
(
Object
x
) {
if ( x == null
)
throw new IllegalArgumentException
( ) ;
if ( size == theArray.length )
doubleQueue (
) ;
size++ ;
back = increment
( back ) ;
return theArray[ back ] = x
;
}
/**
*
Rimuove e restituisce l'oggetto in testa alla coda.
*
@return l'oggetto in testa.
*
@exception EmptyQueueException con coda vuota.
*/
public
Object
dequeue
( ) {
if ( isEmpty
( ) )
throw new EmptyQueueException
( ) ;
size-- ;
Object item =
theArray[ front ] ;
front = increment (
front ) ;
return item ;
}
/**
*
Metodo interno per raddoppiare la dimensione di theArray.
*/
protected
void
doubleQueue
( ) {
Object [ ] newArray
;
newArray = new Object[
theArray.length * 2 ]
;
for ( int i = 0; i < size; i++, front = increment
(
front ) )
newArray[ i ] = theArray[ front ] ;
theArray = newArray ;
front = 0 ;
back = size - 1 ;
}
/**
*Metodo
interno per l'incremento circolare. Restituisce x+1 oppure 0.
*/
protected int increment
( int x
) {
return ( x +
1 ) % theArray.length ;
}
} |