英文:
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<String> stringList = Arrays.asList("a", "b", "c");
private ImmutableList<String> 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<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>)
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<String> stringList = ImmutableList.of("a", "b", "c");
答案2
得分: 1
你可以使用ImmutableList
中的copyOf
函数:
ImmutableList<String> stringList2 = ImmutableList.copyOf(stringList);
英文:
You can use copyOf
function from ImmutableList
ImmutableList<String> stringList2 = ImmutableList.copyOf(stringList);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论