Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 486
DontDivideByZero Avatar asked Mar 11 '15 17:03

DontDivideByZero


1 Answers

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.

like image 199
Rohit Jain Avatar answered Sep 21 '22 14:09

Rohit Jain