Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding elements to ArrayList in Groovy

I am new to Groovy and, despite reading many articles and questions about this, I am still not clear of what is going on. From what I understood so far, when you create a new array in Groovy, the underlying type is a Java ArrayList. This means that it should be resizable, you should be able to initialize it as empty and then dynamically add elements through the add method, like so:

MyType[] list = []
list.add(new MyType(...))

This compiles, however it fails at runtime: No signature of method: [LMyType;.add() is applicable for argument types: (MyType) values: [MyType@383bfa16]

What is the proper way or the proper type to do this?

like image 304
Captain Franz Avatar asked Jun 12 '14 16:06

Captain Franz


People also ask

How do you dynamically add elements to an array?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.

How do I add elements to a list in Groovy?

Groovy - add() Append the new value to the end of this List. This method has 2 different variants. boolean add(Object value) − Append the new value to the end of this List.

How do I add one list to a list in Groovy?

Combine lists using the plus operator The plus operator will return a new list containing all the elements of the two lists while and the addAll method appends the elements of the second list to the end of the first one. Obviously, the output is the same as the one using addAll method.


2 Answers

The Groovy way to do this is

def list = [] list << new MyType(...) 

which creates a list and uses the overloaded leftShift operator to append an item

See the Groovy docs on Lists for lots of examples.

like image 79
doelleri Avatar answered Oct 06 '22 09:10

doelleri


What you actually created with:

MyType[] list = [] 

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4] 

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType()) 

Or more groovy way with overloaded left shift operator:

list << new MyType()  
like image 30
Paweł Piecyk Avatar answered Oct 06 '22 09:10

Paweł Piecyk