0

What is the most efficient and clean way to create an object of a class that has like 10 private fields that are collections (eg. HashMap, LinkedHashMap, ArrayList etc).

If I put a constructor with 10 fields in it it would look like nightmare.

mCs
  • 167
  • 1
  • 4
  • 16

3 Answers3

2

How about a Builder pattern

YourClass obj = YourClass.setCollection1(...)
                           .setCollection2(...)
                             .setCollection3(...)......
                                                  .build();

The added advantage is you just pass the required values and the rest will keep their default values.

rocketboy
  • 9,573
  • 2
  • 34
  • 36
2

You can use a Builder for that like this:

public class Pojo {

    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;

    public Pojo(PojoBuilder pojoBuilder) {
        this.field1 = pojoBuilder.field1;
        this.field2 = pojoBuilder.field2;
        this.field3 = pojoBuilder.field3;
        this.field4 = pojoBuilder.field4;
        this.field5 = pojoBuilder.field5;
    }

    public static class PojoBuilder {
        String field1;
        String field2;
        String field3;
        String field4;
        String field5;

        public PojoBuilder field1(String field1) {
            this.field1 = field1;
            return this;
        }

        public PojoBuilder field2(String field2) {
            this.field2 = field2;
            return this;
        }
        public PojoBuilder field3(String field3) {
            this.field3 = field3;
            return this;
        }
        public PojoBuilder field4(String field4) {
            this.field4 = field4;
            return this;
        }
        public PojoBuilder field5(String field5) {
            this.field5 = field5;
            return this;
        }

        public Pojo build() {
            return new Pojo(this);
        }

    }

    public String getField1() {
        return field1;
    }

    public String getField2() {
        return field2;
    }

    public String getField3() {
        return field3;
    }

    public String getField4() {
        return field4;
    }

    public String getField5() {
        return field5;
    }


}

And you can use it like this:

Pojo pojo = new PojoBuilder().field1("field1").field1("field2").field1("field3").field1("field4").field1("field5").build();

I often use this pattern for building immutable pojos as well.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
0

Consider Builder Pattern

YourClass classObject = new YourClass.name("someName").age(26).Sex("M").build();
Community
  • 1
  • 1
Vikas V
  • 3,176
  • 2
  • 37
  • 60