Resizable Arrays
Invariant
0 <= extent <= buffer.length if extent = 0 then all of the elements of the ResArray are 0. if extent > 0 then buffer[extent - 1] is the last non-zero value in the ResArray.
Interface
public class ResArray {
private int [ ] buffer;
private int extent;
public ResArray ( ) {
extent = 0 ;
buffer = new int [ 0 ] ;
}
public int get ( int i) {
if ( i < extent) {
return buffer[ i] ;
} else {
return 0 ;
}
}
public void set ( int i, int v) {
if ( v == 0 && i >= extent) {
return ;
}
if ( i >= buffer. length) {
grow ( i) ;
}
buffer[ i] = v;
if ( i >= extent) {
extent = i+ 1 ;
}
if ( v == 0 && extent == i+ 1 ) {
shrinkExtent ( i) ;
}
}
private void shrinkExtent ( int i) {
int j = i;
while ( j >= 0 && buffer[ j] == 0 ) {
j-- ;
}
extent = j+ 1 ;
}
private void grow ( int i) {
int newlen = Math. max ( i+ 1 , 2 * buffer. length) ;
int [ ] newbuffer = new int [ newlen] ;
for ( int j= 0 ; j< extent; j++ ) {
newbuffer[ j] = buffer[ j] ;
}
buffer = newbuffer;
}
public int getExtent ( ) {
return extent;
}
public int [ ] values ( ) {
int [ ] values = new int [ extent] ;
for ( int i= 0 ; i< extent; i++ ) {
values[ i] = buffer[ i] ;
}
return values;
}
}