如何将普通List作为ImmutableList?

时间:2016-01-21 02:05:39

标签: java guava immutability

我的下面的Builder模式是线程安全的,并确保在使用ImmutableMap和ImmutableList Guava类分配给parameterMap类后,dataTypeInputKeys无法修改。< / p>

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
}

现在我有两个要求:

  • 如果有人没有调用addEntry方法,那么我的holderEntry列表中只应包含HELLO。
  • 如果有人用一些字符串列表调用addEntry方法,我只想使用他们传递的列表。

根据我目前的设计,让我们说'如果有人传递了包含WORLD字符串的新List,那么我的holderEntry变量包含两个值,一个是HELLO和WORLD,这是错误的。在这种情况下,我想只拥有WORLD。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

为什么不在构建器中默认为holderEntry为空?

InputKeys的构造函数中,您将检查builder.holderEntry是否为空。如果是,您可以将this.holderEntry设置为DEFAULT_TYPE。它也会更高效,更清洁。

Builder

 protected ImmutableList.Builder<String> holderEntry = ImmutableList.<String>builder();

InputKeys构造函数中:

List<String> holderEntry = builder.holderEntry.build();
this.holderEntry = holderEntry.isEmpty() ? DEFAULT_TYPE : holderEntry;