在Groovy中向ArrayList动态添加元素 [英] Dynamically adding elements to ArrayList in Groovy
问题描述
我是Groovy的新手,尽管阅读了许多文章和关于此的问题,但我仍然不清楚发生了什么. 到目前为止,据我了解,当您在Groovy中创建新数组时,底层类型是Java ArrayList.这意味着它应该是可调整大小的,您应该能够将其初始化为空,然后通过add方法动态添加元素,如下所示:
MyType[] list = []
list.add(new MyType(...))
此编译,但是在运行时失败:方法的无签名:[LMyType; .add()适用于参数类型:(MyType)值:[MyType @ 383bfa16]
执行此操作的正确方法或正确类型是什么?
使用Groovy的方法是
def list = []
list << new MyType(...)
创建一个列表并使用重载的列表上的文档. /p>
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?
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.
这篇关于在Groovy中向ArrayList动态添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!