Dynamically adding elements to ArrayList in Groovy

前端 未结 2 398
南笙
南笙 2021-02-04 23:46

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 ar

相关标签:
2条回答
  • 2021-02-05 00:26

    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.

    0 讨论(0)
  • 2021-02-05 00:26

    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() 
    
    0 讨论(0)
提交回复
热议问题