what are the different ways to create an Arraylist and Hashmap in groovy

后端 未结 4 1725
逝去的感伤
逝去的感伤 2021-01-05 02:53

I have created an ArrayList like the following:

def list = new ArrayList()

But the codenarc report it is warning like following.

         


        
4条回答
  •  爱一瞬间的悲伤
    2021-01-05 03:42

    But the codenarc report it is warning like following.

    ArrayList objects are better instantiated using the form "[] as ArrayList"
    

    IMO, this is bad advice on Codenarc's part as it assumes that the implementation type of [] is ArrayList. This is true today, but may not always be.

    The simplest/best/usual way to create a List implementation is:

    def list = []
    

    If possible, I will usually write something like

    List list = []
    

    Just to make it a bit more obvious what this list should contain, i.e. for the sake of code readability. If I wanted to create a specific type of list I would instantiate a List "the Java way"

    List list = new SomeCustomListImplementation()
    

    But in practice I can't remember ever doing this.

提交回复
热议问题