【问题标题】:Combine guava's ImmutableList and varargs结合 guava 的 ImmutableList 和 varargs
【发布时间】:2010-12-25 19:37:11
【问题描述】:

我想创建一个构造函数,它将接受一个或多个整数并将其作为 ImmutableList 保存到字段中。根据 Bloch 的第 42 条“使用可变参数传递一个或多个参数的正确方法”,我创建 smt like

class Foo{
    private final ImmutableList<Integer> bar;
    public Foo(Integer first, Integer... other) {
        this.bar = ImmutableList.<Integer>builder()
                .add(first)
                .addAll(Arrays.asList(other))
                .build();
    }
}

为什么 builder 不会自动获得泛型?而且,因为它闻起来。如何重写?

更新 解决了泛型的问题。任何关于重构的建议都非常有帮助。

【问题讨论】:

    标签: java generics guava variadic-functions


    【解决方案1】:

    因为在调用builder() 时,表达式没有左侧。编译器无法推断要在那里添加什么类型。 (它无法从后续的方法调用中推断出来)

    如果你把它改成下面的,它就可以工作了:

    Builder<Integer> builder = ImmutableList.builder();
    this.bar = builder.add(first).addAll(Arrays.asList(other)).build();
    

    但是,您可以安全地保留当前代码 - 这很好。甚至比上面的例子更好(更短)

    关于重构 - 为什么不使用.add(first).add(other)add 方法有一个可变参数版本。

    【讨论】:

      【解决方案2】:

      关于您的第二个问题(如何重构构造函数以使其更短/更具可读性),我会这样做:

      class Foo{
          private final ImmutableList<Integer> bar;
          public Foo(Integer first, Integer... other) {
              this.bar = ImmutableList.copyOf(Lists.asList(first, other));
          }
      }
      

      根据他们的 javadoc,Lists.asList 方法的设计都考虑到了这个目标:

      这在使用可变参数方法时很有用 需要使用签名,例如 (Foo firstFoo, Foo... moreFoos), 按顺序 避免过载歧义或 强制执行最小参数计数。

      它也比 ImmutableList.Builder 更高效,因为它避免了在 Builder 中创建/调整临时 ArrayList 的大小。


      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-14
        • 2011-05-15
        • 1970-01-01
        相关资源
        最近更新 更多