如何将ImmutableList创建为成员变量?

huangapple go评论77阅读模式
英文:

How can I create an ImmutableList as a member variable?

问题

我需要创建一个ImmutableList作为成员变量。

以下是我尝试过的代码:

private List<String> stringList = Arrays.asList("a", "b", "c");
private ImmutableList<String> stringList2 = Collections.unmodifiableList(stringList);

这会导致编译错误:

FakeRemoteDataStore.java:59: error: incompatible types: no instance(s) of type variable(s) T exist so that List<? extends T> conforms to ImmutableList<String>
private ImmutableList<String> stringList2 = Collections.unmodifiableList(stringList);
                                                                      ^
where T is a type-variable:
T extends Object declared in method <T>unmodifiableList(List<? extends T>)

我如何在成员变量中创建ImmutableList

英文:

I need to create an ImmutableList as a member variable.

Here's what I tried:

  private List&lt;String&gt; stringList = Arrays.asList(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);
  private ImmutableList&lt;String&gt; stringList2 = Collections.unmodifiableList(stringList);

This fails to compile with the error:

FakeRemoteDataStore.java:59: error: incompatible types: no instance(s) of type variable(s) T exist so that List&lt;T&gt; conforms to ImmutableList&lt;String&gt;
  private ImmutableList&lt;String&gt; stringList2 = Collections.unmodifiableList(stringList);
                                                                          ^
  where T is a type-variable:
    T extends Object declared in method &lt;T&gt;unmodifiableList(List&lt;? extends T&gt;)

How can I create an ImmutableList as a member variable?

答案1

得分: 1

ImmutableList是Guava的一部分,因此您可以直接这样做:

private ImmutableList<String> stringList = ImmutableList.of("a", "b", "c");
英文:

ImmutableList is part of Guava, so you can just do:

private ImmutableList&lt;String&gt; stringList = ImmutableList.of(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);

答案2

得分: 1

你可以使用ImmutableList中的copyOf函数:

ImmutableList<String> stringList2 = ImmutableList.copyOf(stringList);
英文:

You can use copyOf function from ImmutableList

ImmutableList&lt;String&gt; stringList2 = ImmutableList.copyOf(stringList);

huangapple
  • 本文由 发表于 2020年9月23日 01:07:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64014513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定