I have a String array in a Groovy class (args to a main method):
String[] args
I’d like to convert the 3rd to the last element into a new array of ints. Is there an easier way to do this in Groovy other than:
final int numInts = args.length - 2
final int [] intArray = new int[numInts]
for (int i = 2; i < args.length; i++) {
intArray[i-2]=Integer.parseInt(args[i])
}
I wanted to do:
final int numInts = args.length - 2
final int [] intArray = new int[numInts]
System.arraycopy(args, 2, intArray, 0, numInts)
But it throws a class cast exception.
Thanks!
This is my solution:
The
2..-1range selects all elements from the 3rd to the last. Thecollectmethod transforms every element of the array using the code in the closure. The lastas int[]converts the List of integers that results from the collect method into an array of integers. As Groovy doesn’t work with primitive types, theints will always be stored asjava.lang.Integers, but you can work with them, as if they were Java primitives. The conversion from a List to an array is optional. As Collections are first class citizens in Groovy and are much easier to work with as in Java, I’d prefer to work directly with Lists than arrays.EDIT:
Alternatively, you can replace the
collectmethod with the so called spread operator*., but you have to use the methodasType(int)instead of the short versionas int: