Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 682
srini Avatar asked Jun 28 '11 13:06

srini


2 Answers

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 = [:] 
like image 172
tim_yates Avatar answered Oct 29 '22 21:10

tim_yates


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

like image 25
Eric Wilson Avatar answered Oct 29 '22 23:10

Eric Wilson