Builders for immutable collections (*List). [message #1783177] |
Thu, 08 March 2018 15:20  |
Eclipse User |
|
|
|
Hi all,
I commonly come across cases where I need to mutably build a large list of items within a single method, then "finalize it" as an immutable list to return.
I'd like to be able to do without having to copy the items like toImmutableList() would when called on the mutable lists. The mutable "builder" form of the thing doesn't have to conform to any specific interfaces other than having an "add" method for my purposes - and it would give up it's reference to the data when building the immutable list. Is there any way of doing this currently, or would such a feature be considered as an enhancement?
Thanks,
Steve
|
|
|
Re: Builders for immutable collections (*List). [message #1804584 is a reply to message #1783177] |
Thu, 28 March 2019 23:45  |
Eclipse User |
|
|
|
Hi Steve,
Sorry for the delay in responding to your question. There is no way to do this today, in terms of returning the ImmutableList interface after building up a MutableList without doing a final copy. However, you can use asUnmodifiable() as follows, which will simply adapt the MutableList with an unmodifiable adapter.
MutableList<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5).asUnmodifiable();
If you don't want to expose the mutating methods, you can additionally return ListIterable<Integer>.
ListIterable<Integer> integers = Lists.mutable.with(1, 2, 3, 4, 5).asUnmodifiable();
Hope that helps.
Thanks,
Don
[Updated on: Fri, 29 March 2019 00:34] by Moderator
|
|
|
Powered by
FUDForum. Page generated in 0.03032 seconds