Doing what you suggest would break the entire concept of equals
/hashCode
tandem. Both equals
and hashCode
would be rendered useless and should not even exist.
Java allows the programmer to define the equality sets for his class; if he doesn't want to do it, he can simply opt out of overriding equals
and hashCode
βand end up with exactly the semantics you propose.
To give a specific example, under your proposal, this would create two separate entries in the map:
Map<Integer, String> map = new HashMap<>();
map.put(10_000, "a");
map.put(10_000, "a");
That is because the literal 10_000 will be autoboxed each time into a new instance of Integer
, which, under your semantics, are two separate keys. And then, the statement
System.out.println(map.get(10_000));
would print null
, because of course you are using a third key to get. It would in fact be impossible to retrieve any map value by key.