Why Does My HashMap Return Null Even When the Key Exists?

Profile Picture

Henrique Sa

OP
Admin
@riquelds.bsky.social
3 days ago

This should return "John", but I'm getting null. What’s wrong with my HashMap logic?

Map<Integer, String> map = new HashMap<>();
map.put(1, "John");

Integer id = new Integer(1);  
System.out.println(map.get(id)); // prints null
java oop rest-api
Profile Picture
2 days ago

Making an integer with the constructor Integer() is depreciated.

Try making id like:

int id = 1;