How do I create an empty Guava ImmutableList?

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>?

Answers


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.


ImmutableList.<Foo>of() will create an empty ImmutableList with generic type Foo. Though the compiler can infer the generic type in some circumstances, like assignment to a variable, you'll need to use this format (as I did) when you're providing the value for a function argument.


Since Java 8 the compiler is much more clever and can figure out the type parameters parameters in more situations.

Example:

void test(List<String> l) { ... }

// Type checks in Java 8 but not in Java 7
test(ImmutableList.of()); 
Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference. (Most of the time, one exception is assignments.)

In this case the parameter type of test will be the target type for of(), and the return value type of of will get chosen to match that argument type.


Need Your Help

Setting request timeout for JAX-RS 2.0 Client API

java rest jax-rs

I have written simple REST web service client class which uses the JAX-RS 2.0 client API to make REST requests. I am trying to figure out how to set a request timeout for each invocation. Here is the

Android: Theme Holo previous version

java android styles themes

I really like the 4.0 ICS Holo Light theme and would like to have it in my app to support &lt;4.0 smartphones.