Arrays in Groovy

In Groovy, arrays are similar to those in other languages, but Groovy also provides more flexible and powerful collection types like Lists, which are more commonly used. However, arrays are still useful in certain scenarios.

// In Groovy, we don't need to declare a main method or class explicitly
// for simple scripts. The code will run from top to bottom.

// Here we create an array 'a' that will hold exactly 5 integers.
// By default, an array is initialized with null values for object types,
// or 0 for primitive types like int.
def a = new int[5]
println "emp: $a"

// We can set a value at an index using the array[index] = value syntax,
// and get a value with array[index].
a[4] = 100
println "set: $a"
println "get: ${a[4]}"

// The size property returns the length of an array.
println "len: ${a.size()}"

// Use this syntax to declare and initialize an array in one line.
def b = [1, 2, 3, 4, 5] as int[]
println "dcl: $b"

// Groovy provides a shorthand syntax for creating arrays
b = [1, 2, 3, 4, 5]
println "dcl: $b"

// In Groovy, you can use the spread operator (*) to initialize an array with specific values
b = [100, *[0, 0, 0], 400, 500] as int[]
println "idx: $b"

// Array types are one-dimensional, but you can compose types to build
// multi-dimensional data structures.
def twoD = new int[2][3]
for (i in 0..<2) {
    for (j in 0..<3) {
        twoD[i][j] = i + j
    }
}
println "2d: $twoD"

// You can create and initialize multi-dimensional arrays at once too.
twoD = [
    [1, 2, 3],
    [4, 5, 6]
] as int[][]
println "2d: $twoD"

When you run this Groovy script, you should see output similar to this:

emp: [0, 0, 0, 0, 0]
set: [0, 0, 0, 0, 100]
get: 100
len: 5
dcl: [1, 2, 3, 4, 5]
dcl: [1, 2, 3, 4, 5]
idx: [100, 0, 0, 0, 400, 500]
2d: [[0, 1, 2], [1, 2, 3]]
2d: [[1, 2, 3], [4, 5, 6]]

Note that arrays in Groovy are objects and have methods like size(). The syntax for creating and manipulating arrays is similar to Java, but Groovy provides some additional convenient ways to work with arrays, such as the spread operator and more flexible initialization syntax.

Groovy also has strong support for other collection types like Lists and Maps, which are often more flexible and commonly used than arrays in Groovy code. However, arrays are still useful when working with Java libraries or when dealing with fixed-size collections of primitive types for performance reasons.