Groovy中动态添加元素到ArrayList

编程入门 行业动态 更新时间:2024-10-28 02:36:35
本文介绍了Groovy中动态添加元素到ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我是 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 09:59:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884890.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   动态   Groovy   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!