RFR: 8186958: Need method to create pre-sized HashMap [v5]

XenoAmess duke at openjdk.java.net
Thu Mar 24 16:50:49 UTC 2022


On Thu, 24 Mar 2022 16:44:50 GMT, XenoAmess <duke at openjdk.java.net> wrote:

>> src/java.base/share/classes/java/util/HashMap.java line 2556:
>> 
>>> 2554:      */
>>> 2555:     static int calculateHashMapCapacity(int expectedSize) {
>>> 2556:         if (expectedSize >= 1610612736) {
>> 
>> It would be clearer with a comment on the constant or use the expression (the compiler will evaluate it).
>> `Integer.MAX_VALUE / 4 * 3`.
>> 
>> There also might be a valid point to make about a fail-fast exception if the requested capacity cannot be achieved.   If defaulted to MAX_VALUE, the application would start populating the map and then at some later point get an exception when it cannot be resized to accommodate the n+1'th item.
>
>> It would be clearer with a comment on the constant or use the expression (the compiler will evaluate it). `Integer.MAX_VALUE / 4 * 3`.
> 
> @RogerRiggs 
> 
> No, as `Integer.MAX_VALUE / 4 * 3` is actually 1610612733,
> 
> and `(int)Math.ceil(1610612733/0.75)` is actually 2147483644, 
> 
> while `Integer.MAX_VALUE` is 2147483647
> 
> Although in this situation 2147483644 and 2147483647 is same (both would be trimed down to 1073741824 when enter the HashMap constructor), but I think it be better to be more precise.
> 
> However if you want me to change it to `expectedSize >= Integer.MAX_VALUE / 4 * 3 + 3`, then I think it acceptable, but looks a little weird.
> 
> So should we change it to `expectedSize >= Integer.MAX_VALUE / 4 * 3 + 3`?

> There also might be a valid point to make about a fail-fast exception if the requested capacity cannot be achieved. If defaulted to MAX_VALUE, the application would start populating the map and then at some later point get an exception when it cannot be resized to accommodate the n+1'th item.

@RogerRiggs 

No, as I want 100% same reaction to use these functions like using new HashMap(int)

So as the HashMap constructor itself doesn't throw exception when oversize, this function shall neither.

-------------

PR: https://git.openjdk.java.net/jdk/pull/7928


More information about the core-libs-dev mailing list