Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why initialize HashSet<>(0) to zero?

Tags:

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?

like image 935
Dimitri Dewaele Avatar asked Aug 06 '13 09:08

Dimitri Dewaele


People also ask

What is the default fill ratio of HashSet?

HashSet<Integer> hs = new HashSet<Integer>(10,(double)0.50); The second argument called the "Fill Ratio" has a default value of 0.75.

What is the default initial capacity and initial load factor of HashSet object?

Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor (0.75).

How HashSet increases its size?

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.


2 Answers

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.

like image 52
Joni Avatar answered Sep 22 '22 16:09

Joni


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.

like image 34
lichengwu Avatar answered Sep 19 '22 16:09

lichengwu