array in groovy

Arrays in Groovy

In Groovy, an array is a fixed-size collection of elements of the same type. Here's how you can create and work with arrays in Groovy:

1. Creating an Array: You can create an array in Groovy using the [] syntax or the array() method. For example:

def numbers = [1, 2, 3, 4, 5] // Using square brackets
def fruits = array("apple", "banana", "orange") // Using the array() method

2. Accessing Array Elements: You can access individual elements of an array using the index. The index starts from 0 for the first element. For example:

def numbers = [1, 2, 3, 4, 5]
def firstNumber = numbers[0] // Accessing the first element
def thirdNumber = numbers[2] // Accessing the third element

3. Modifying Array Elements: You can modify the elements of an array by assigning new values to specific indices. For example:

def numbers = [1, 2, 3, 4, 5]
numbers[2] = 10 // Modifying the third element

4. Array Length: You can get the length of an array using the length property. For example:

def numbers = [1, 2, 3, 4, 5]
def length = numbers.length // Getting the length of the array

5. Iterating Over an Array: You can iterate over the elements of an array using a loop, such as a for loop or a each closure. For example:

def numbers = [1, 2, 3, 4, 5]
for (number in numbers) {
    println(number)
}

6. Array Methods: Groovy provides various methods to work with arrays, such as sort(), reverse(), contains(), and join(). For example:

def numbers = [5, 2, 4, 1, 3]
numbers.sort() // Sorting the array in ascending order
def isPresent = numbers.contains(3) // Checking if the array contains a specific element
def joinedString = numbers.join(", ") // Joining the elements of the array into a string

Please note that the examples provided above are for illustration purposes and may not cover all possible use cases. For more detailed information and additional array operations, you can refer to the Groovy documentation.