58

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?

2 Answers 2

80

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Ok this works. Actually also list.add(new MyType(...)) works if you define the list like this. But I have a comment and a question. Comment: so there is no way of specifying what type you are going to put in the list when you create it? Question: why does it work in this way and it doesn't if I specify a type? It looks as if it were using a different underlying type then ArrayList in that case.
You can use List<MyList> list = [], but if you're not using CompileStatic, it will basically be ignored
You can also def list = [new MyType(...)]
33

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() 

2 Comments

Thanks. So is there no way of creating a dynamic list with a specific type?
The question is already answered by tim_yates in a comment to the second answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.