package
lab2;
/**
*
Classe ArrayStack :
*
* Realizzazione
del TDA Pila mediante array.
*/
public class ArrayStack
implements
Stack
{
static
final int DEFAULT_SIZE
= 32 ;
protected
Object
[ ] theArray ;
protected
int
top ;
/**
*
Costruttore della pila.
*/
public
ArrayStack
( ) {
theArray = new Object [
DEFAULT_SIZE ]
;
top = -1 ;
}
/**
*
Verifica che la pila sia logicamente vuota.
*
@return <code>true</code> se la pila è vuota;
*
<code>false</code> altrimenti.
*/
public
boolean
isEmpty
( ) {
return top == -1 ;
}
/**
*
Svuota la pila.
*/
public
void
clear
( ) {
top = -1 ;
}
/**
*
Restituisce l'oggetto in cima alla pila senza estrarlo.
*
@return l'oggetto in cima.
*
@exception EmptyStackException con pila vuota.
*/
public
Object
peek
( ) {
if ( isEmpty
( ) )
throw new EmptyStackException
( ) ;
return theArray [ top ] ;
}
/**
*
Inserisce un oggetto in cima alla pila.
*
@param x l'oggetto da inserire.
*
@return l'oggetto inserito.
*
@exception IllegalArgumentException se l'argomento passato
*
è <code>null</code>.
*/
public
Object
push
( Object x
) {
if (
x
== null )
throw new IllegalArgumentException
( ) ;
if ( top == theArray.length - 1 )
doubleArray
(
) ;
return theArray [ ++top ] = x ;
}
/**
*
Rimuove e restituisce l'oggetto in cima alla pila.
*
@return l'oggetto in cima.
*
@exception EmptyStackException con pila vuota.
*/
public
Object
pop
( ) {
if ( isEmpty
( ) )
throw new EmptyStackException
( ) ;
return theArray [ top-- ] ;
}
/**
*
Metodo interno per raddoppiare la dimensione di theArray.
*/
protected
void
doubleArray
( ) {
Object
[ ] newArray ;
newArray = new Object [
theArray.length * 2 ]
;
for ( int i = 0; i < theArray.length; i++ )
newArray[ i ] = theArray [ i ] ;
theArray = newArray ;
}
} |