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

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -