Stas Kurilin Stas Kurilin - 1 year ago 74
Java Question

Combine guava's ImmutableList and varargs

I want create constructor that will take one or more integers and save it into field as ImmutableList. According to "The right way to use varargs to pass one or more arguments" by Bloch's Item 42 I create smt like

class Foo{
private final ImmutableList<Integer> bar;
public Foo(Integer first, Integer... other) { = ImmutableList.<Integer>builder()

Why builder doesn't get generic automatically? And, as it smells. How I can rewrite it?

qustion with generics solved. Any suggestions about refactoring are very helpful.

Answer Source

Because the when calling builder() there is no left-hand side of the expression. The compiler cannot infer what type to add there. (It cannot infer it from subsequent method calls)

If you change it to the following, it works:

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

However, you can safely retain your current code - it is fine. And even better than the above example (it's shorter)

About the refactoring - why not use .add(first).add(other)? The add method has a varargs version.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download