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

Roger Riggs rriggs at openjdk.java.net
Thu Mar 24 17:12:48 UTC 2022


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

>>> 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.

I'm not too picky about how it is documented, as long as it is clear how the number 1610612733 is computed and why its the correct number. And I think that's working backward from Integer.MAX_VALUE.
As for its precision, its almost irrelevant since the actual size must be a power of two; and precision is only important near the boundary of a power of two. A simple and obvious explanation is better than one that is overly precise (when it matters).

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

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


More information about the core-libs-dev mailing list