Groovy中动态添加元素到ArrayList [英] Dynamically adding elements to ArrayList in Groovy

查看:37
本文介绍了Groovy中动态添加元素到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Groovy 的新手,尽管阅读了很多关于此的文章和问题,但我仍然不清楚发生了什么.根据我目前的理解,当您在 Groovy 中创建一个新数组时,底层类型是 Java ArrayList.这意味着它应该是可调整大小的,您应该能够将其初始化为空,然后通过 add 方法动态添加元素,如下所示:

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

此编译,但在运行时失败:没有方法签名:[LMyType;.add() 适用于参数类型:(MyType) 值:[MyType@383bfa16]

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?

推荐答案

Groovy 的方法是

The Groovy way to do this is

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

创建一个列表并使用重载的 leftShift 操作符附加一个项目

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

请参阅 Groovy 列表上的文档以获取大量示例.

See the Groovy docs on Lists for lots of examples.

这篇关于Groovy中动态添加元素到ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆