Java – combines immutablelist and varargs of guava

I want to create a constructor that will use one or more integers and save it as a field immutablelist According to Bloch's item 42, "pass one or more parameters using varargs in the correct way", I created 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();
    }
}

Why doesn't the builder automatically get the generic, and it smells How can I rewrite it?

UPD generics solved the problem Any advice on refactoring is very helpful

Solution

Because there is no left side of the expression when calling Builder () The compiler cannot infer what types are added there (it cannot be inferred from subsequent method calls)

It works if you change it to the following:

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

However, you can safely keep the current code - that's okay Even better (shorter) than the above example

About refactoring – why not Add (first) Add (other)? The add method has a varargs version

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>