Guava ImmutableList copyOf vs Builder
I don't see any reason why you should use builder here:
ImmutableList.copyOf
is much more readable than making aBuilder
in this case,Builder
doesn't infer generic type and you have to specify type by yourself when used as one-liner,- (from docs)
ImmutableList.copyOf
does good magic when invoked with another immutable collection (attempts to avoid actually copying the data when it is safe to do so), - (from source)
Builder#addAll
invokesaddAll
on previously createdArrayList
whilecopyOf
avoids creating any list for zero- and one-element collections (returns empty immutable list and singleton immutable list respectively), - (from source)
copyOf(Collection)
instance doesn't create temporaryArrayList
(copyOf(Iterable)
andcopyOf(Iterator)
does so), - (from source) moreover,
Builder#build
invokescopyOf
on previously internally populatedArrayList
, what brings you to your question - why useBuilder
here, when you havecopyOf
?
P.S. Personally I use ImmutableList.builder()
static factory instead of new ImmutableList.Builder<Blah>()
constructor - when assigned to a Builder<Blah>
variable the first infers generic type while the latter doesn't.