Using Java Arrays

Creating new Java arrays

To allocate a Java array you can use the array type specifier as a constructor function. For example, to allocate an array with room for 10 elements each of each is a primitive int:

(int[] length: 10)

You can specify the initial elements instead of the length:

(object[] 31 32 33 34)

This creates a 4-length array, initialized to the given values.

Note this is a variation of the generation object-allocation (see Allocating objects) pattern. You can explicitly use the make function, if you prefer:

(make object[] 31 32 33 34)

If you specify a length, you can also specify initial values for selected elements. If you specify an index, in the form of a literal integer-valued keyword, then following elements are placed starting at that position.

(int[] length: 100 10 12 80: 15 16 50: 13 14)

This creates an array with 100 elements. Most of them are initialized to the default value of zero, but elements with indexes 0, 1, 50, 51, 80, 81 are initialized to the values 10, 12, 13, 14, 15, 16, respectively.

Accessing Java array elements

You can access the elements of a Java array by treating it as a one-argument function, where the argument is the index:

(define primes (integer[] 2 3 5 7 11 13))
(primes 0) ⇒ 2
(primes 5) ⇒ 13

You can set an element by treating the array as a function with a setter:

(set! (primes 0) -2)
(set! (primes 3) -7)
primes ⇒ [-2 3 5 -7 11 13]

To get the number of elements of an array, you can treat it as having a length field:

primes:length ⇒ 6

Here is a longer example. This is the actual definition of the standard gcd function. Note the args variable receives all the arguments on the form of an integer array. (This uses the Java5 varargs feature.)

(define (gcd #!rest (args ::integer[])) ::integer
  (let ((n ::int args:length))
    (if (= n 0)
	0
	(let ((result ::integer (args 0)))
	  (do ((i ::int 1 (+ i 1)))
	      ((>= i n) result)
	    (set! result (gnu.math.IntNum:gcd result (args i))))))))

The above example generates good code, thanks to judicious use of casts and type specifications. In general, if Kawa knows that a “function” is an array then it will generate efficient bytecode instructions for array operations.

Old low-level array macros

The deprecated Low-level array macros are also supported.