Why do I get an OutOfMemoryError when inserting 50,000 objects into HashMap?

前端 未结 10 1932
猫巷女王i
猫巷女王i 2021-02-01 08:12

I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a java.util.HashMap. However, I keep getting an OutOfMemo

10条回答
  •  [愿得一人]
    2021-02-01 08:51

    Another thing to try if you know the number of objects beforehand is to use the HashMap(int capacity,double loadfactor) constructor instead of the default no-arg one which uses defaults of (16,0.75). If the number of elements in your HashMap exceeds (capacity * loadfactor) then the underlying array in the HashMap will be resized to the next power of 2 and the table will be rehashed. This array also requires a contiguous area of memory so for example if you're doubling from a 32768 to a 65536 size array you'll need a 256kB chunk of memory free. To avoid the extra allocation and rehashing penalties, just use a larger hash table from the start. It'll also decrease the chance that you won't have a contiguous area of memory large enough to fit the map.

提交回复
热议问题