Why initialize HashSet<>(0) to zero?

前端 未结 5 1210
半阙折子戏
半阙折子戏 2021-02-07 02:50

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

Set users = new HashSet<>();
         


        
5条回答
  •  我在风中等你
    2021-02-07 03:47

    HashSet use HashMap store data:

    public HashSet(int initialCapacity) {
    map = new HashMap(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.

提交回复
热议问题