What is the difference between HashMap and Array?

What is the difference between HashMap and Array?

  • Search efficiency
    HashMap directly calculates the index according to the value of the hashcode, so its search efficiency increases as the length of the array increases.
    ArrayMap uses the dichotomy method. When the length of the array doubles, one more judgment is made, and the efficiency decreases.

  • The initial value of the expansion quantity
    HashMap is 16 lengths, and each time the capacity is expanded, double the array space is directly applied.
    Each time ArrayMap expands, if the size length is greater than 8, apply for size*1.5 lengths, if it is greater than 4 and less than 8, apply for 8 lengths, and if it is less than 4, apply for 4 lengths. Compared with ArrayMap in this way, it actually applies for less memory space, but the frequency of expansion will be higher. Therefore, if the amount of data is relatively large, it is more appropriate to use HashMap, because its expansion times are much less than that of ArrayMap.

  • Expansion efficiency
    HashMap recalculates the position of each array member each time it expands, and then puts it in a new position.
    ArrayMap uses System.arraycopy directly, so ArrayMap must be more efficient in terms of efficiency.

  • Memory consumption
    ArrayMap adopts a unique method, which can reuse the array space left over from data expansion to facilitate the use of the next ArrayMap. And HashMap does not have this design. Since ArrayMap caches lengths of 4 and 8, if Map is frequently used and the amount of data is relatively small, ArrayMap is undoubtedly quite memory-saving.

      总结
      综上所述,数据量比较小,并且需要频繁的使用Map存储数据的时候,推荐使用ArrayMap。 而数据量比较大的时候,则推荐使用HashMap。
    

Guess you like

Origin blog.csdn.net/TC_DESpipi/article/details/128713100