HashMap expansion steps, 2 times expansion

HashMap expansion:

  • advantage:
    1. Improved the load factor of the hash table: When expanding, HashMap will recalculate hash values ​​and reallocate bucket bits, thereby reducing the possibility of hash conflicts and improving query performance.
    2. Support more elements: Expansion allows HashMap to accommodate more elements, making it more efficient when storing large amounts of data.
  • shortcoming:
    1. Memory consumption: Expansion requires reallocation of larger memory space, which may lead to increased memory usage, especially when the amount of data stored in HashMap is large.
    2. The expansion operation is time-consuming: Due to the need to recalculate hash values ​​and reallocate bucket positions, the expansion process may take some time, especially if there are a large number of elements.
      HashMap<String, Integer> hashMap = new HashMap<>(16);  // 初始容量为16
      
      // 添加元素到HashMap
      hashMap.put("apple", 10);
      hashMap.put("banana", 20);
      hashMap.put("orange", 30);
      
      // 扩容操作
      if (hashMap.size() >= hashMap.capacity()) {
          int newCapacity = hashMap.capacity() * 2;  // 计算新容量
          hashMap.resize(newCapacity);  // 创建新桶位数组并重新分配元素
      }
      

Guess you like

Origin blog.csdn.net/Feixiangdechenyu/article/details/131257029