srini
srini

Reputation: 6969

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

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?

Upvotes: 11

Views: 31489

Answers (4)

Eric Wilson
Eric Wilson

Reputation: 59425

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 [:].

Upvotes: 11

D&#243;nal
D&#243;nal

Reputation: 187399

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.

Upvotes: 5

tim_yates
tim_yates

Reputation: 171194

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 = [:] 

Upvotes: 18

Andrey Adamovich
Andrey Adamovich

Reputation: 20683

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

def list = [] as ArrayList

Upvotes: 1

Related Questions