java – 结合番石榴的ImmutableList和varargs
发布时间:2020-12-14 16:46:31 所属栏目:Java 来源:网络整理
导读:我想要创建构造函数,它将使用一个或多个整数,并将其保存为字段为ImmutableList.根据Bloch的第42项“正确的方式使用varargs传递一个或多个参数”,我创建了smt class Foo{ private final ImmutableListInteger bar; public Foo(Integer first,Integer... other
我想要创建构造函数,它将使用一个或多个整数,并将其保存为字段为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 解决方法
因为当调用builder()时没有表达式的左侧.编译器不能推断什么类型添加到那里. (它不能从随后的方法调用中推断出)
如果您将其更改为以下内容,则它可以正常工作: Builder<Integer> builder = ImmutableList.builder(); this.bar = builder.add(first).addAll(Arrays.asList(other)).build(); 但是,您可以安全地保留当前的代码 – 没关系.甚至比上面的例子更好(更短) 关于重构 – 为什么不使用.add(第一).add(其他)? add方法有一个varargs版本. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |