java 如何创建一个空的 Guava ImmutableList?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29776576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:55:24  来源:igfitidea点击:

How do I create an empty Guava ImmutableList?

javagenericsguavaimmutablelist

提问by zigg

I can create a Guava ImmutableListwith the ofmethod, and will get the correct generic type based on the passed objects:

我可以使用该方法创建一个番石榴ImmutableListof,并将根据传递的对象获得正确的泛型类型:

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

However, the ofmethod with no parameterscannot infer the generic type and creates an ImmutableList<Object>.

但是,没有参数of方法无法推断泛型类型并创建一个ImmutableList<Object>.

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

我怎样才能创造一个空ImmutableList来满足List<Foo>

回答by ColinD

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()像@zigg 所说的那样编写。

回答by zigg

ImmutableList.<Foo>of()will create an empty ImmutableListwith generic type Foo. Though the compiler can infer the generic typein 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.

ImmutableList.<Foo>of()将创建一个ImmutableList具有泛型类型的空Foo。尽管编译器可以在某些情况下推断出泛型类型,例如对变量的赋值,但是当您为函数参数提供值时,您将需要使用这种格式(就像我所做的那样)。

回答by Lii

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

由于Java 8,编译器更加聪明,可以在更多情况下计算出类型参数参数。

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 typeof 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.)

Java 8 中的新事物是表达式的目标类型将用于推断其子表达式的类型参数。在 Java 8 之前,只有用于类型参数推断的方法的参数。(大多数情况下,一个例外是分配。)

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

在这种情况下, 的参数类型test将是 的目标类型of(),并且 的返回值类型of将被选择以匹配该参数类型。