views:

114

answers:

2

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!

A: 

For your alternative - you try to copy String objects to integers. That is not possible and you get what you deserve - a ClassCastException ;-)

At least within Java - System.arraycopy only works with compatible array types.

Your first approach is not bad. If the code looks too ugly, just hide it in a private method with a signature like:

private int[] parseStrings(String[] args, int start);
Andreas_D
+1  A: 

This is my solution:

def intArray = args[2..-1].collect { it as int } as int[]

The 2..-1 range selects all elements from the 3rd to the last. The collect method transforms every element of the array using the code in the closure. The last as 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, the ints will always be stored as java.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 collect method with the so called spread operator *., but you have to use the method asType(int) instead of the short version as int:

def intArray = args[2..-1]*.asType(int) as int[]
Christoph Metzendorf
Cool, thank you!
Cuga