0

I was reading about HashMap. HashCodereturns int value. What if i have Huge Huge HashMap, which needs to store more objects than int range. Consider that for every object HashCode() method will returns unique value. In this case what will happen

  1. Is any exception thrown ? Or
  2. It will behave randomly?
Rogger296
  • 147
  • 3
  • 15
  • 1
    https://stackoverflow.com/questions/11113871/what-happens-if-hashcode-calculated-exceeds-the-integer-max-limit – LuisFerrolho Nov 29 '17 at 12:53
  • Check [How many elements can I store in a HashMap object in Java](https://stackoverflow.com/questions/19886017/how-many-elements-can-i-store-in-a-hashmap-object-in-java) – Deepak Pandey Nov 29 '17 at 12:55
  • Not sure, but Java 8+ increased the side of arrays to be of Long.MAX_INT, so it's probably the new limit – Marcos Vasconcelos Nov 29 '17 at 13:06

1 Answers1

0

You mean storing more than 2 billion entries? Java collections or maps can't do this, their size is always an int value.

There are 3rd party libraries for huge maps.

Are you sure you can store these many objects in memory anyway? One object takes at least 24 bytes (you will be out of the range of Compressed OOPS), so you will be using beyond 100 gigabytes of RAM, and that is with very small objects stored in the HashMap.

PS: I don't understand what you mean with "hashCode returning a unique value". Hash codes don't have to be unique. For a 2+ billion entry hash map, a 32 bit hash code is a bit weak, but still theoretically possible.

Stefan Reich
  • 1,000
  • 9
  • 12