【问题标题】:How can I create an ImmutableList as a member variable?如何创建一个 ImmutableList 作为成员变量?
【发布时间】:2021-01-08 20:40:24
【问题描述】:

我需要创建一个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<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 作为成员变量?

【问题讨论】:

  • ImmutableList 是一个单独的类型,与 java.util.Collections 返回的内容不兼容。试试stringList2 = ImmutableList.copyOf(stringList)
  • 什么是ImmutableList?一定是 Java SE 之外的东西。

标签: java arrays collections


【解决方案1】:

你可以使用ImmutableList中的copyOf函数

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

【讨论】:

  • 是的,但stringList 是不必要的中间变量。
  • 同意,我们可以避免这个中间变量。我们这里有两种不同的答案,如果有人想创建一个新列表,他可以参考上面的答案,如果有人已经有一个列表,那么他可以使用这个答案。
【解决方案2】:

ImmutableList 是 Guava 的一部分,所以你可以这样做:

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

【讨论】:

  • 或者你可以做什么YCF_L said,根本不使用第三方库。
  • 非常感谢您的快速回复。我正在编辑一个现有的代码库,但不知道它正在使用 Guava 类。搜索“create an ImmutableList in Java”会显示关于“不可变列表”的答案,而不是特定的 Guava 类ImmutableList,因此我感到困惑。希望这个答案能帮助其他处于类似情况的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-20
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多