Jeeter
Jeeter

Reputation: 6105

Builders - creates a new instance each time?

I'm using a couple of Builders to make a bunch of objects. What I'm currently doing is this:

List<ProductofBuilder> list;
Builder b = new Builder();

for(some iterable i in I) {
    b.setSomeParam(i);
    list.add(b.build());
}

Is this okay to do? In other words, does a builder create a new instance of ProductOfBuilder each build()?

Upvotes: 2

Views: 508

Answers (2)

Jeeter
Jeeter

Reputation: 6105

So I wasn't totally clear in the question that I was building each time. Sorry about that.

Running this code:

    ArrayList<ScanSettings> list = new ArrayList<>();
    ScanSettings.Builder b = new ScanSettings.Builder();
    for (int i = 0; i < 10; i++) {
        b.setReportDelay(i * 100);
        list.add(b.build());
    }

gives the following result in the debugger.

enter image description here

so they all have unique memory addresses, and each one has the unique reportDelay too.

Upvotes: 0

Blackbelt
Blackbelt

Reputation: 157467

Is this okay to do? In other words, does a builder create a new instance of ProductOfBuilder each

No it is not. Accordingly to the code you posted you are changing always the same reference. In the end your list will contains n builder, with the content of the last call to setSomeParam.

It is different if you have a Collection of objects the builder is supposed to build, and you are calling at every iteration build().

List<TypeToBuild> list;
TypeToBuild.Bilder builder;
for (Type t : parmas) {
   builder.setParamns(t);
   list.add(builder.build());
 }

Upvotes: 2

Related Questions