结合番石榴的ImmutableList和varargs

时间:2010-12-25 19:37:12

标签: java generics guava variadic-functions

我想要创建构造函数,它将获取一个或多个整数并将其作为ImmutableList保存到字段中。根据Bloch的第42项中“使用varargs传递一个或多个论点的正确方法”,我创建了像smt一样的

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();
    }
}

为什么构建器不会自动获得通用?而且,因为它闻起来。我怎么能改写它?

UPD 解决了仿制药的问题。任何有关重构的建议都非常有用。

2 个答案:

答案 0 :(得分:14)

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

如果您将其更改为以下内容,则可以:

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

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

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

答案 1 :(得分:8)

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

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

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

  

这在varargs方法时很有用   需要使用诸如(Foo   firstFoo,Foo ... moreFoos),按顺序   避免过载模糊或   强制执行最小参数计数。

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


相关问题