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?
HashSet<Integer> hs = new HashSet<Integer>(10,(double)0.50); The second argument called the "Fill Ratio" has a default value of 0.75.
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).
The HashSet capacity is doubled when the load factor (0.75) is reached. As the documentation explains: The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased.
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.
HashSet use HashMap store data:
public HashSet(int initialCapacity) {
map = new HashMap<E,Object>(initialCapacity);
}
while the initialCapacity = 0,
public HashMap(int initialCapacity, float loadFactor) {
....
// Find a power of 2 >= initialCapacity
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
}
the HashMap capacity is 1
.
but if use default constructor:
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
the HashMap capacity is 16*0.75
.
So, new HashSet<>(0)
save some memroy when init.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With