Timber | Implementation | Spar | Overview | foreach | arrays | array expressions | inline | Vectors | Templates | array interface | elastic array interface | example | Sins |
An array type is written as the name of an element type, followed by a number of abstract shape specifications. For example:
int[*] v; // A 1-dimensional array int[*,*] A; // A 2-dimensional array
For compatibility with Java, Spar also allows Java-style declarations of one-dimensional arrays:
int[] n; // A 1-dimensional array
This is a special case.
Here are some examples of declarations of array variables that create array objects:
int a[*] = new int[4]; short b[*,*] = new short[6,8]; int sq[*] = { 1, 4, 9, 16, 25, 36 }; real ident[*,*] = {{1,0,0}, {0,1,0}, {0,0,1}}; real vv[*][*] = {{1,0,0}, {0,1,0}, {0,0,1}}; String[] aos = { "array", "of", "string" };
Note that ident
and vv
have the same initialization
expression, but they are not equivalent. The first is a
two-dimensional array, the second is a one-dimensional array of
one-dimensional arrays.
A component of an array is accessed by an expression
that consists of an array reference followed by an int
vector
expression, as in: A[i,j]
. All arrays start at element 0. A
one-dimensional array with length n can be indexed by the integers 0
to n-1.
For example, the following assigns 2 to array element [2,3]
of
array A
.
int[*,*] A = new int[9,9]; // A 2-dim array A[2,3] = 2; // An array access
This looks very similar to array access in other languages, but in the case of Spar this is a special case of a more general access construct, where arbitrary vector expressions can be used to access an array. Since any vector expression can be used, very powerful access expressions are possible. This is demonstrated in the following code:
int[*,*] A = new int[9,9]; // A 2-dim array [int^2] v = [1,1]; // A vector of 2 elm. A@v = 3; // A[1,1] = 3 A@(3*v) = 4; // A[3,3] = 4
As much as possible, array accesses are checked for bounds
violations at compile time. If the array access cannot be
checked at compile time, an index that is out of bounds causes an
IndexOutOfBoundsException
to be thrown.
Last modified Sat May 13 15:50:56 2017 UT by Kees van Reeuwijk.