Java Groovy 中动态添加元素到 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24189193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:41:40  来源:igfitidea点击:

Dynamically adding elements to ArrayList in Groovy

javalistarraylistgroovy

提问by Captain Franz

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:

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

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]

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

What is the proper way or the proper type to do this?

这样做的正确方法或正确类型是什么?

采纳答案by doelleri

The Groovy way to do this is

这样做的 Groovy 方法是

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

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

它创建一个列表并使用重载leftShift运算符来附加一个项目

See the Groovy docs on Listsfor lots of examples.

有关大量示例,请参阅列表上的 Groovy文档

回答by Pawe? Piecyk

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:

是大小为 0 的固定大小数组(不是列表)。您可以使用以下命令创建大小为 4 的固定大小数组:

MyType[] array = new MyType[4]

But there's no add method of course.

但是当然没有添加方法。

If you create list with defit's something like creating this instance with Object(You can read more about defhere). And []creates empty ArrayListin this case.

如果你用def它创建列表就像用它创建这个实例Object(你可以def在这里阅读更多信息)。并在这种情况下[]创建空ArrayList

So using def list = []you can then append new items with add()method of ArrayList

因此,使用def list = []您可以使用以下add()方法附加新项目ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

或者使用重载左移运算符的更时髦的方式:

list << new MyType()