DontDivideByZero
DontDivideByZero

Reputation: 1211

Guava ImmutableSet: Builder vs. of?

The Javadoc for com.google.common.collect.ImmutableSet suggests that there are two ways to create instances of ImmutableSet<E> from elements of type E (e.g. E e1 and E e2) that are not already in a collection (i.e. ignoring the copyOf method to create from existing collection):

  1. The "of" method:

    ImmutableSet<E> set = ImmutableSet.of(e1, e2);
    
  2. Builder:

    ImmutableSet<E> set = new ImmutableSet.Builder<E>().add(e1).add(e2).build();
    

Both methods use ImmutableSet.Builder#construct in the end but which one should I prefer?

Upvotes: 10

Views: 10839

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213261

It completely depends upon how you're going to build ImmutableSet. If you've all the elements available at one place, then directly use of(E...) method. That would certainly be shorter.

But if somehow, you're getting elements from different places, that would mean, your object state is not finalized at one place, but after accumulating data on the flow. Then you will have to go with Builder way. Create a Builder, and keep on adding elements as and when you get. And then when you're done, just call build() to get ImmutableSet.

Upvotes: 16

Related Questions