Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I comfortably fill a List with new Objects in Groovy?

Tags:

java

list

groovy

I want to create a List with 10 different objects of a certain class in Groovy. In Java there is Arrays.fill but I'm certain there is a much more elegant way in Groovy.

I tried this:

def mylist = [new MyClass()]*10;

But that gives me the same reference for every Item in the List.

like image 575
unSinn Avatar asked Aug 31 '25 23:08

unSinn


1 Answers

I ended up using @cfrick's version:

def l = ([MyClass]*10)*.newInstance()

assert l.size() == 10
assert l.unique().size() == 10

It fits on one line and is readable.

like image 103
unSinn Avatar answered Sep 03 '25 14:09

unSinn