【问题标题】:Returning a new ImmutableList that is an existing list plus an extra element返回一个新的 ImmutableList,它是一个现有的列表加上一个额外的元素
【发布时间】:2015-05-05 09:51:16
【问题描述】:

我正在使用 Google 的 ImmutableList 类 http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableList.html

我正在寻找一种方法,它采用现有的 ImmutableList 和一个额外的元素(相同类型),并返回一个包含旧元素和新元素的 new ImmutableList。

也许我在文档中遗漏了一些明显的东西?

【问题讨论】:

    标签: java immutablelist


    【解决方案1】:
    public static final ImmutableList<Foo> result
       = new ImmutableList.Builder<Foo>()
           .addAll(originalList)
           .add(new Foo())
           .build();
    

    【讨论】:

    • 但这并没有做任何结构共享 - 它只是创建一个具有相同元素的新列表。
    • 是的。但结构共享不是 OP 问题的一部分。而且我不认为 ImmutableList 支持它。
    • 这不是 OP 问题的明确部分,但他确实在问题中添加了一个标签“结构共享”。我同意 Guava 的 ImmutableList 不支持这个。
    • 是的,遗憾的是 ImmutableList 不做结构共享,但不是必须的。列表包含不到 20 个元素。
    【解决方案2】:

    你可以这样做:

    ImmutableList<YourType> newList = ImmutableList.copyOf(
        Iterables.concat(existingList, ImmutableList.of(newElement))
    );
    

    编辑: @JB Nizets 解决方案看起来更具可读性:)

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 2018-11-18
      • 2016-06-21
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多