11

I have created an ArrayList like the following:

def list = new ArrayList()

But the codenarc report it is warning like following.

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

What are the better ways to instantiate the collections?

Eric Wilson
59.7k82 gold badges208 silver badges272 bronze badges
asked Jun 28, 2011 at 13:45

4 Answers 4

18

You can do:

def list = [] // Default is ArrayList
def list = [] as ArrayList
ArrayList list = []

And again, for HashMap:

HashMap map = [:]
def map = [:] as HashMap

The default in this case is a LinkedHashMap:

def map = [:] 
answered Jun 28, 2011 at 13:51

2 Comments

no need of putting ':' simply we can write the same as def map = [] as HashMap
@Oda True, but I wouldn't use that as I couldn't say whether it will always work in future versions
11

Typical is:

def list = []

other options include

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

and of course:

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

Similar options exist for HashMap using [:].

answered Jun 28, 2011 at 13:49

2 Comments

It should be List list = [] as ArrayList, I mean when using [] as XYZ, parenthesis are not included at the end
@Mahesha999 and four years later, my error is corrected! Thanks, I've edited.
5

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<String> 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<String> list = new SomeCustomListImplementation<String>()

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

answered Jun 28, 2011 at 14:21

1 Comment

+1 I agree with almost all of what you say, but I don't think that parametrized types List<String> give as much benefit in Groovy as in Java. I feel like either def list = [] or List list = [] fits better with the Groovy mindset.
1

Why don't you just use a suggestion from codenarc?

def list = [] as ArrayList
answered Jun 28, 2011 at 13:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.