Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an empty Guava ImmutableList?

Tags:

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

like image 322
zigg Avatar asked Apr 21 '15 15:04

zigg


People also ask

How do I create an empty ImmutableList?

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.

How do you create an empty immutable list in Java?

We can use the List. of() to create an immutable empty list.


2 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.

like image 68
ColinD Avatar answered Sep 30 '22 19:09

ColinD


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.

like image 26
zigg Avatar answered Sep 30 '22 18:09

zigg