在groovy中创建Arraylist和Hashmap有哪些不同的方法

在groovy中创建Arraylist和Hashmap有哪些不同的方法,groovy,Groovy,我创建了一个ArrayList,如下所示: def list = new ArrayList() 但codenarc报告警告如下 ArrayList objects are better instantiated using the form "[] as ArrayList" 实例化集合的更好方法是什么?典型的方法是: def list = [] 其他选择包括 def list = new ArrayList() def list = new ArrayList<Foo>()

我创建了一个ArrayList,如下所示:

def list = new ArrayList()
但codenarc报告警告如下

ArrayList objects are better instantiated using the form "[] as ArrayList"
实例化集合的更好方法是什么?

典型的方法是:

def list = []
其他选择包括

def list = new ArrayList()
def list = new ArrayList<Foo>()
List list = new ArrayList()
def list = [] as ArrayList
List list = [] as ArrayList
当然:

List<Foo> list = new ArrayList<Foo>();

使用[:]的HashMap也有类似的选项。

为什么不使用codenarc的建议呢

def list = [] as ArrayList
你可以做:

def list = []               // Default is ArrayList
def list = [] as ArrayList
ArrayList list = []
同样,对于HashMap:

本例中的默认值是LinkedHashMap:

但codenarc报告警告如下

ArrayList objects are better instantiated using the form "[] as ArrayList"
依我看,这对Codenarc来说是个错误的建议,因为它假设[]的实现类型是ArrayList。这在今天是正确的,但可能并不总是如此

创建列表实现的最简单/最佳/常用方法是:

def list = []
如果可能的话,我通常会写一些

List<String> list = []

但实际上,我不记得曾经这样做过。

不需要加“:”就可以简单地编写与def map=[]相同的代码HashMap@Oda是的,但我不会使用它,因为我不能说它在未来的版本+1中是否总是有效。我几乎同意你所说的所有内容,但我认为参数化类型列表在Groovy中的好处不如在Java中。我觉得def list=[]或list list=[]更适合Groovy的思维模式。它应该是list list=[]作为ArrayList,我的意思是当使用[]作为XYZ时,括号不包括在end@Mahesha999四年后,我的错误被纠正了!谢谢,我编辑过。
def list = []
List<String> list = []
List<String> list = new SomeCustomListImplementation<String>()