user2782001
user2782001

Reputation: 3498

Groovy how to push value to array of type long

New to groovy so take it easy... I get an error that there is no push() method for an array of longs

def mylongs=[] as long[];
somebject.each{
     //logic to chooose...
     mylongs.push(it.thisisalong);
}

So how do I append long values properly. Using

 mylongs[mylongs.size()]=it.thisisalong  

yields out of index bounds exceptions

Upvotes: 1

Views: 10127

Answers (3)

Luis Muñiz
Luis Muñiz

Reputation: 4811

First let me address your second question, and the larger difference between Arrays and Lists in the JVM:

Arrays, and lists in Java are 0-based, meaning that the first element can be found in a[0], and the last element, in a[a.size()-1]. Element a[a.size()] exceeds the bounds of your array, and that is what your exception tells you.

In groovy you can use a.last(), if you want to pick up the last element of an array/list, in my opinion it is more readable and self-explanatory.

If you cast your mylongs into an array before populating it, then you have fixed the size of the array, and you can push no more objects into it. If your array has variable size, then you need to use a List.

List<Long> a=[]

a << 1 as long
a << 2 as long

etc

When you need to convert it back to an array, you can do this:

a as long[]

Now to the answer of the first question, the others pretty much gave you a valid answer, but in groovy style, i'd write (providing that somebject is a collection of some type):

def mylongs= somebject.collect{ it.thisisalong } as long[]

But pushing an element into an List and be done like this, in groovy style:

myLongs << 4

You cannot append values into an array, it has a fixed size.

Upvotes: 6

dmahapatro
dmahapatro

Reputation: 50275

mylongs = someobject*.thisisalong as long[]

should do. *. is spread operator in groovy.

Upvotes: 2

user2782001
user2782001

Reputation: 3498

I ended up doing this.

 def mylongs=[];
 somebject.each{
      //logic to chooose...
      mylongs.add(it.thisisalong as long);
 }

Upvotes: 1

Related Questions