Returning a new ImmutableList that is an existing list plus an extra element

我的梦境 提交于 2019-12-14 03:57:31

问题


I'm using Google's ImmutableList class http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableList.html

I'm looking for a method which takes an existing ImmutableList and an extra element (of the same type), and returns a new ImmutableList that contains the old elements plus the new one.

Perhaps I'm missing something obvious in the docs?


回答1:


public static final ImmutableList<Foo> result
   = new ImmutableList.Builder<Foo>()
       .addAll(originalList)
       .add(new Foo())
       .build();



回答2:


You could do it the following way:

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

Edit: @JB Nizets solution looks more readable :)



来源:https://stackoverflow.com/questions/28853935/returning-a-new-immutablelist-that-is-an-existing-list-plus-an-extra-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!