简体   繁体   中英

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

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.

mylongs = someobject*.thisisalong as long[]

should do. *. is spread operator in groovy .

I ended up doing this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM