1

Just came up upon a very strange behavior of Java HashMap. The map has the Long type of keys, but when I access them passing an int key, there is no autocast, instead the get() method returns null as if the key does not exist! Why Java does no proper auto casting from int to long in this case?

Halmeru
  • 13
  • 2

2 Answers2

2

Map.get() and remove() accept any object. Your int is being auto-boxed to Integer

It doesn't know what you meant to write is map.get((Long) (long) intValue) or map.get((long) intValue)

If you are using primitive types, rather than objects, you can try TLongObjectHashMap which does convert int to long (not the wrappers)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

The get method of the HashMap accepts an Object, regardless of the generic type. The reason behind that has been explained in a different Stackoverflow question.

In your case, the int is auto boxed to an Integer object. However, as only Long objects are stored in your map, no object for the Integer object is found. As the get method accepts any object, there is no way to know that the int should be casted to a Long. This may(!) be different if the get method would only accepts Long objects. You have to cast it yourself.

Community
  • 1
  • 1
dmeister
  • 34,704
  • 19
  • 73
  • 95