Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava ImmutableList copyOf vs Builder

Tags:

java

guava

I was wondering which is more efficient and why?

1)

List<Blah> foo;
...
return ImmutableList.copyOf(foo);

or

2)

List<Blah> foo;
...
return new ImmutableList.Builder<Blah>().addAll(foo).build();
like image 517
user973479 Avatar asked Mar 01 '12 13:03

user973479


People also ask

Is immutable list ordered?

Immutable List Static Factory Methods. The List. of static factory methods provide a convenient way to create immutable lists. A list is an ordered collection, where duplicate elements are typically allowed.

How do you make a collection immutable?

In Java 8 and earlier versions, we can use collection class utility methods like unmodifiableXXX to create immutable collection objects. If we need to create an immutable list then use the Collections. unmodifiableList() method.


1 Answers

I don't see any reason why you should use builder here:

  • ImmutableList.copyOf is much more readable than making a Builder 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 invokes addAll on previously created ArrayList while copyOf 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 temporary ArrayList (copyOf(Iterable) and copyOf(Iterator) does so),
  • (from source) moreover, Builder#build invokes copyOf on previously internally populated ArrayList, what brings you to your question - why use Builder here, when you have copyOf?

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.

like image 56
Xaerxess Avatar answered Sep 30 '22 18:09

Xaerxess