So I was working on a programming challenge where I wanted to store more than 128 key-value pairs of type <int, int>.
Since HashMaps can't accept primitives, I used <Integer, Integer
>. I ran into a problem where I'd go:
HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();
Integer x = new Integer(130);
map.put(x, x);
Later on in my code, I compute the value I need to retrieve from the map as an integer. I try to retrieve it using:
int calculated = 130;
Integer y = new Integer(calculated);
map.get(y)
This will cause a NullPointerException because the HashCode of the x and y are different (which is expected because the Integer class keeps a cache of values only between -128 and 127).
My question is if I want to store a large number of key-value pairs using a map-like structure in Java, how would I do so?
[EDIT]: Thank you everyone for your responses! After having refactored some of my logic, the problem no longer exists (it wasn't a problem with the Integer itself). Thanks for making me appreciate using HashMaps in Java again :)
This will cause a NullPointerException because the HashCode of the x and y are different (which is expected because the Integer class keeps a cache of values only between -128 and 127).
That's irrelevant. Integer
overrides hashCode()
and equals()
appropriately, which is all that's required for non-identical objects to be looked up in a HashMap
. (The hash codes of two equal Integer
values will be the same, even if they're not the same Integer
objects.)
It should be absolutely fine:
Map<Integer, Integer> map = new HashMap<>();
Integer x = 130;
Integer y = 130;
System.out.println(x == y); // False (on my machine)
map.put(x, 1000);
System.out.println(map.get(y)); // 1000
Additionally, just the statement map.get(y)
will not throw a NullPointerException
unless map
or y
is null
... even if it can't find a match, it will return null
, not throw an exception.
Note that you don't need to call new Integer(...)
- and if you do, the caching for boxed values is irrelevant anyway. For example:
Integer a = new Integer(5);
Integer b = new Integer(5);
System.out.println(a == b); // False, always
Integer c = 5;
Integer d = 5;
System.out.println(c == d); // True, always, due to caching of small boxed values
See more on this question at Stackoverflow