How do I create an empty Guava ImmutableList?

zigg picture zigg · Apr 21, 2015 · Viewed 20k times · Source

I can create a Guava ImmutableList with the of method, and will get the correct generic type based on the passed objects:

Foo foo = new Foo();
ImmutableList.of(foo);

However, the of method with no parameters cannot infer the generic type and creates an ImmutableList<Object>.

How can I create an empty ImmutableList to satisfy List<Foo>?

Answer

ColinD picture ColinD · Apr 21, 2015

If you assign the created list to a variable, you don't have to do anything:

ImmutableList<Foo> list = ImmutableList.of();

In other cases where the type can't be inferred, you have to write ImmutableList.<Foo>of() as @zigg says.