Why initialize HashSet<>(0) to zero?

Dimitri Dewaele picture Dimitri Dewaele · Aug 6, 2013 · Viewed 8.5k times · Source

I love a HashSet<>() and use this eagerly while initializing this with the default constructor:

Set<Users> users = new HashSet<>();

Now, my automatic bean creator (JBoss tools) initializes this as:

Set<Users> users = new HashSet<>(0);

Why the zero? The API tells me that this is the initial capacity, but what is the advantage of putting this to zero? Is this advised?

Answer

Joni picture Joni · Aug 6, 2013

The default initial capacity is 16, so by passing in 0 you may save a few bytes of memory if you end up not putting anything in the set.

Other than that there is no real advantage; when you pass 0 the set is created with a capacity of 1 and as soon as you add something it will have to be resized.