def testArray = new String[3] testArray[0] = "A" testArray[1] = "B" testArray[2] = "C"
We can also define an array by declaring it's type. Even when the value uses the syntax of a list, it will automatically be converted to an array:
String[] testArray = ["A", "B", "C"]
We can also use as syntax for explicit coercion.
def testArray = ["A", "B", "C"] as String[]
Here is an alternative syntax to convert the type
def testArray = (String[]) ["A", "B", "C"]
We can also use the toArray() method of a list. But the result is an array of objects and not an array of specific class. E.g. array of Strings.
def testArray = ["A", "B", "C"].toArray()
Here is an example of using toArray but the result will be a String array instead of an Object array.
def testArray = ["A", "B", "C"].toArray(new String[0])
String[] testArray = ["A", "B", "C"] println testArray.length
We can also invoke the size() method similar to collections.
String[] testArray = ["A", "B", "C"] println testArray.size()
String[] testArray = ["A", "B", "C"] println testArray[0] println testArray.getAt(0)
This will both get the first element. Here is the output of the code:
A A
We can use negative index that will wrap around
String[] testArray = ["A", "B", "C"] println testArray[-1] println testArray.getAt(-1)
Here is the output of the code:
C C
Here is another example on how negative index works:
String[] testArray = ["A", "B", "C"] println testArray[0] println testArray[1] println testArray[2] println testArray[-1] println testArray[-2] println testArray[-3]
Here is the output of the code:
A B C C B A
As always, we can't access beyond the last element.
String[] testArray = ["A", "B", "C"] println testArray[3]
This will throw an exception as we can only access 0, 1, and 2.
Caught: java.lang.ArrayIndexOutOfBoundsException: 3
This negative index will also throw an exception:
String[] testArray = ["A", "B", "C"] println testArray[-4]
Here is the output of the code when run:
Caught: java.lang.ArrayIndexOutOfBoundsException: Negative array index [-4] too large for array size 3
It is simple to get the lowest value item on an array. Here is an example:
Integer[] intArray = [200, 300, 100] println intArray.min() String[] stringArray = ["A", "B", "C"] println stringArray.min()
Here is the output:
100 A
Similarly, there is a convenience method to get the highest value element on the array. Here is an example:
Integer[] intArray = [200, 300, 100] println intArray.max() String[] stringArray = ["A", "B", "C"] println stringArray.max()
Here is the output:
300 C
There is also a built-in method to sort the elements in the array. Here is an example code:
Integer[] intArray = [200, 300, 100] println intArray intArray.sort() println intArray
Here is the output:
[200, 300, 100] [100, 200, 300]
We can also reverse items on an array. Here is an example:
String[] stringArray = ["A", "B", "C"] String[] reverseArray = stringArray.reverse() println stringArray println reverseArray
Here is the output:
[A, B, C] [C, B, A]