简体   繁体   中英

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 (eg E e1 and E e2 ) that are not already in a collection (ie 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM