Returning a new ImmutableList that is an existing

2019-07-21 04:03发布

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?

2条回答
别忘想泡老子
2楼-- · 2019-07-21 04:39
public static final ImmutableList<Foo> result
   = new ImmutableList.Builder<Foo>()
       .addAll(originalList)
       .add(new Foo())
       .build();
查看更多
Viruses.
3楼-- · 2019-07-21 04:47

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 :)

查看更多
登录 后发表回答