java - How to make normal List as ImmutableList? -


i have below builder pattern thread safe , making sure parametermap , datatype cannot modified after being assigned inputkeys class using immutablemap , immutablelist guava class.

public final class inputkeys {      private final long userid;     private final long clientid;     private final list<string> holderentry;      private static final immutablelist<string> default_type = immutablelist.of("hello");          private inputkeys(builder builder) {         this.userid = builder.userid;         this.clientid = builder.clientid;         this.holderentry = builder.holderentry.build();     }      public static class builder {         protected final long clientid;         protected long userid;         protected immutablelist.builder<string> holderentry = immutablelist.<string>builder().addall(default_type);          public builder(inputkeys key) {             this.clientid = key.clientid;             this.userid = key.userid;             this.holderentry = immutablelist.<string> builder().addall(key.holderentry);         }                     public builder(long clientid) {             this.clientid = clientid;         }          public builder setuserid(long userid) {             this.userid = long.valueof(userid);             return this;         }                 public builder addentry(list<string> holderentry) {             this.holderentry.addall(holderentry);             return this;         }                     public inputkeys build() {             return new inputkeys(this);         }     }      // getters here } 

now have 2 requirements:

  • if not calling addentry method holderentry list should have hello in it.
  • if calling addentry method list of string, want use list passing.

with current design, let' if passes new list has world string in holderentry variable contains 2 values 1 hello , world wrong. in scenario want have world only. how fix issue?

why not leave holderentry empty default in builder?

and in constructor of inputkeys check if builder.holderentry empty. if so, set this.holderentry default_type. more efficient , cleaner too.

in builder:

 protected immutablelist.builder<string> holderentry = immutablelist.<string>builder(); 

in inputkeys constructor:

list<string> holderentry = builder.holderentry.build(); this.holderentry = holderentry.isempty() ? default_type : holderentry;  

Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -