Spar - the ElasticArray interface

spar

If a class wants to allow growing and shrinking like that of ordinary arrays, it should implement the ElasticArray interface:

interface ElasticArray(| type t, int n |) extends Array(| t, n |)
{
    void setSize( [int^n] sz ) throws NegativeArraySizeException;
    int getRoom();                                                  
    void setRoom( int rm );                                         
    void setRoom( [int^n] rm );                               
    void fitRoom();              
}
The main difference with normal arrays is that the user can specify a new array size with the setSize method. This will grow or shrink the array, while preserving elements that are visible before and after the change of size.

For efficiency reasons it is possible to allocate more more elements to an array than is necessary to store an array of the current size. The user can request more room with the setRoom methods, query the current room with the getRoom method, or release superfluous room with the fitRoom method.

Standard Spar arrays implement this interface, but it can also be implemented by user-defined classes. See the SimpleArray class definition for an example.

To demonstrate the use of the ElasticArray interface, the function listPositives below returns a new array of appropriate size that contains all positive elements of the given array.

Note that in this example the array grows one element a time. A real-life function will try to be smarter than that by reserving room in the array in advance.

public class Demo
{
    public static double[] listPositives( double l[] )
    {
	double res[] = new double[0];
	int pos = 0;

	for( int ix=0; i<l.size; ix++ ){
	    if( l[ix]>0 ){
		res.setSize( [pos+1] );
		res[pos++] = l[ix];
	    }
	}
	return res;
    }

    static void main( String argv[] )
    {
	double arr[] = { 1, -1, 3, -66, 2, 0, -3, 2, 6 };

	System.out.println( "Result: "+listPositives( arr ) );
    }
}

Last modified Sat May 13 15:50:56 2017 UT by Kees van Reeuwijk.