5

In java, hashcode() method, returns integer instead of long. Is there any specific reason?

dgupta3091
  • 1,067
  • 1
  • 7
  • 18
  • What would be the advantage in producing a long? Your hash table is not going to contain over 2 billion buckets. – khelwood Mar 26 '18 at 10:23
  • @khelwood Something like this I wrote maybe 10 years ago.... and guess what: I was told that the company has hundreds of billions items in their table (obviously not JDK HashMap). – maaartinus Mar 26 '18 at 18:59

2 Answers2

10

Well, one good reason is that the hashCode based data structures (HashSet, HashMap) use an array to store the bins, and arrays are limited to int indices. You will gain nothing by a long hashCode() if you must map it to an int array index.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Yes, but since many years, this is insufficient for some users, who need a custom huge Map (obviously using multiple arrays or off-heap). Java is simply old, that's it. – maaartinus Mar 26 '18 at 19:02
3

Using the hashCode is to have N buckets where the hashCode % N determines the bucket of elements, hopefully being 1 (no conflicting hashCodes).

For N, for the hash code, an int is entirely sufficient; indeed one needs to have most variety in the lower bits; having a long without using the higher bits (when N would be a power of 2), would be counter productive.

Speed of course is a requirement too: int being slightly better on the final CPU.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138